#include<iostream>
#include<cstdio> #include<cstring> #include<queue> using namespace std; #define INF 0x7f struct node{ int x, y; int cont; }; bool inq[8][8]; node cb[9][9]; char s1[3],s2[3]; int sx, sy, ex, ey, dx, dy; int d[8][2]= {{1,2},{1,-2},{2,1},{2,-1},{-1,2},{-1,-2},{-2,1},{-2,-1}}; void init(){ for(int i = 0; i <= 8; i++) for(int j = 0; j <= 8; j++){ cb[i][j].x = i; cb[i][j].y = j; cb[i][j].cont = 0; } } int change(char w){ int b; if(w == 'a') b = 1; if(w == 'b') b = 2; if(w == 'c') b = 3; if(w == 'd') b = 4; if(w == 'e') b = 5; if(w == 'f') b = 6; if(w == 'g') b = 7; if(w == 'h') b = 8; return b; } bool check(int x, int y){ if(x > 0&&x <= 8&&y > 0&&y <= 8&&!inq[x][y]){ return true; } else return false; } void bfs(){ memset(inq, false, sizeof(inq)); queue<node> q; init(); q.push(cb[sx][sy]); node rec; inq[sx][sy] = true; while(!q.empty()){ rec = q.front(); q.pop(); if(rec.x == ex&&rec.y == ey) break; for(int i = 0; i < 8; i++){ dx = rec.x + d[i][0]; dy = rec.y + d[i][1]; if(check(dx,dy)) { inq[dx][dy] = true; cb[dx][dy].cont = rec.cont+1; q.push(cb[dx][dy]); } } } } int main(){ while(scanf("%s%s",&s1,&s2) != EOF){ sx = change(s1[0]); ex = change(s2[0]); sy = s1[1] - '0'; ey = s2[1] - '0'; bfs(); printf("To get from %s to %s takes %d knight moves.\n",s1,s2,cb[ex][ey].cont); } return 0; }
水的模板BFS,题意就不多解释了,只要知道“马走日”这一规则就可以了,一定会走到终点。
写完后我才发现我逗比地写了一个change()函数,T^T算了,今天逗比了好多次。
末,多谢小建建耐心地帮忙找bug~~~T^T
作者:u011652573 发表于2014-3-26 16:56:09 原文链接
阅读:43 评论:0 查看评论