非常典型的bfs
#include <iostream> #include <queue> #include <cstring> using namespace std; int n; int grid[100][100]={0}; int move[8][2]={{2,1},{1,2},{-2,1},{-1,2},{2,-1},{1,-2},{-1,-2},{-2,-1}}; int sx,sy,ex,ey; struct Cell { int x,y; Cell(int a=0,int b=0):x(a),y(b){} }; //Cell last_cell[10][10]; int bfs() { queue<Cell> Q; Cell cc(sx,sy); Q.push(cc); while(!Q.empty()) { Cell c=Q.front(); int _x=c.x,_y=c.y; for(int i=0;i<8;i++) { int xx=_x+move[i][0],yy=_y+move[i][1]; if(xx<1||yy<1||xx>8||yy>8||grid[xx][yy]) continue; grid[xx][yy]=grid[_x][_y]+1; Cell t(xx,yy); // last_cell[xx][yy]=c; Q.push(t); if(xx==ex&&yy==ey) return grid[xx][yy]; } Q.pop(); } return -1; } int main() { char A,C; int B,D; while(cin>>A>>B>>C>>D) { sx=A-'a'+1;sy=B; ex=C-'a'+1;ey=D; memset(grid,0,sizeof(grid)); int steps=0; if(!(sx==ex&&sy==ey)) steps=bfs(); cout<<"To get from "<<A<<B<<" to "<<C<<D<<" takes "<<steps<<" knight moves."<<endl; } return 0; }
由这道题延伸出去,如果打印出路径:
有两种办法,递归和非递归,前提都需要用一个数组来存下该路径的点。
Cell ccc(ex,ey);
last_cell[xx][yy]=c;
上述代码中被我注释掉的两行。
下面分别是打印路径的代码。
递归:
void print_path(Cell c) { if(c.x==sx&&c.y==sy) {cout<<c.x<<' '<<c.y<<endl; return;} print_path(last_cell[c.x][c.y]); cout<<"x:"<<c.x<<" y:"<<c.y<<endl; }
void print_path2(Cell c) { int nn=0; Cell dir[100]; while(1) { dir[nn++]=c; if(c.x==sx&&c.y==sy) break; c=last_cell[c.x][c.y]; } for(int i=nn-1;i>=0;i--) { cout<<dir[i].x<<' '<<dir[i].y<<endl; } }