题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1372
变量名不能使用next,这与系统的命名冲突。。(这我还第一次知道orz涨姿势了)
还有就是估计是昨晚刚开完例会回来,脑子有点问题,居然用swtich case 来转换字母。。然后还不小心吧g敲成j 然后WA..
再次复习bfs的模板:
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; int d[8][2]= {{1,2},{1,-2},{2,1},{2,-1},{-2,1},{-2,-1},{-1,2},{-1,-2}}; int visit[10][10]; int sx,sy,ex,ey; char c1,c2; struct state { int x,y; int step; }cur,next1; void bfs(state temp) { temp.step = 0; queue<state> q; q.push(temp); visit[temp.x][temp.y] = 1; while(!q.empty()) { cur = q.front(); if(cur.x == ex && cur.y == ey) { printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,sy,c2,ey,cur.step); return ; } for(int i = 0;i < 8;i++) { next1.x = cur.x + d[i][0]; next1.y = cur.y + d[i][1]; next1.step = cur.step + 1; if(next1.x>=1&&next1.x<=8&&next1.y>=1&&next1.y<=8&&!visit[next1.x][next1.y]) { q.push(next1); visit[next1.x][next1.y] = 1; } } q.pop(); } } using namespace std; int main() { while(cin >> c1 >> sy >> c2 >> ey) { memset(visit,0,sizeof(visit)); sx=c1-'a'+1; ex=c2-'a'+1; /*switch (c1) { case 'a': sx = 1; break; case 'b': sx = 2; break; case 'c': sx = 3; break; case 'd': sx = 4; break; case 'e': sx = 5; break; case 'f': sx = 6; break; case 'g': sx = 7; break; //之前写成case 'j' WA得妥妥的。。 case 'h': sx = 8; break; } switch (c2) { case 'a': ex = 1; break; case 'b': ex = 2; break; case 'c': ex = 3; break; case 'd': ex = 4; break; case 'e': ex = 5; break; case 'f': ex = 6; break; case 'g': ex = 7; break; case 'h': ex = 8; break; }*/ cur.x = sx; cur.y = sy; bfs(cur); } return 0; }