题目大意:在一个8*8的国际想起内,你是国际象棋中马这个角色,然后行从1-8,列从a-h编号,给出起点和终点,问你的最短路径。(马走日子)
思路:简单的bfs,被scanf(“%s%s”)卡了两次,玄学,改成scanf(" %c %c %c %c",&s1[0],&s1[1],&s2[0],&s2[1])就过来,思路还是挺简单的。
代码:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int maze[9][9];
int vis[9][9];
char s1[2],s2[2];
int dir[8][2]={{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}};
struct node{
int x,y;
node(int a,int b):x(a),y(b){}
node(){}
};
bool inside(int x,int y){
return (x>=1&&x<=8&&y>=1&&y<=8);
}
int main(){
int id1,id2;
while(scanf(" %c %c %c %c",&s1[0],&s1[1],&s2[0],&s2[1])!=EOF){
memset(maze,0,sizeof(maze));
memset(vis,0,sizeof(vis));
sscanf(&s1[1],"%d",&id1);
sscanf(&s2[1],"%d",&id2);
queue<node>st;
st.push(node(id1,s1[0]-'a'+1));
while(!st.empty()){
node now=st.front();
st.pop();
if(now.x==id2&&now.y==(s2[0]-'a'+1)){
cout<<"To get from "<< s1[0]<<s1[1]<< " to "<< s2[0]<<s2[1]<<" takes "<< maze[now.x][now.y]<<" knight moves."<<endl;
break;
}
for(int i=0;i<8;i++){
int fx=now.x+dir[i][0];
int fy=now.y+dir[i][1];
if(!vis[fx][fy]&&inside(fx,fy)){
st.push(node(fx,fy));
vis[fx][fy]=1;
maze[fx][fy]=maze[now.x][now.y]+1;
}
}
}
}
}