zoj 1091 BFS简单搜索
/* 题意:knight从一个位置移动到另一位置,求最少移动多少步 题解:BFS */ #include <cstdio> #include <cstring> #include <queue> using namespace std; int dir[8][2] = {{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};//八个方向 bool m[10][10]; struct point { int x,y; int deep; }; int bfs(int sx, int sy, int ex, int ey) { if (sx == ex && sy == ey) return 0; struct point start,end; start.x = sx; start.y = sy; start.deep = 0; end.x = ex; end.y = ey; memset(m,false,sizeof(m)); queue<struct point> Q; Q.push(start); int ret = 0; bool flag = false; while (!Q.empty()) { struct point tmp,t = Q.front(); Q.pop(); m[t.x][t.y] = true; for(int i=0; i<8; i++) { int tx = t.x+dir[i][0]; int ty = t.y+dir[i][1]; if (1<=tx && tx<=8 && 1<=ty && ty<=8 && !m[tx][ty]) { if (tx == ex && ty == ey) return t.deep+1; tmp.x = tx; tmp.y = ty; tmp.deep = t.deep+1; Q.push(tmp); m[tx][ty] = true; } } } return ret; } int main(void) { char s1[5],s2[5]; while (scanf("%s%s",s1,s2) == 2) { printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs(s1[0]-'a'+1,s1[1]-'0',s2[0]-'a'+1,s2[1]-'0')); } return 0; }