zoj1091

来源:互联网 发布:儿童网络投票策划方案 编辑:程序博客网 时间:2024/05/29 19:26

    广度优先搜索的题,感觉挺简单的,每个Knight就跟中国象棋里的马一样,走日字型,在每个地方可以往八个方向走(如果不越界的话)

#include <stdio.h>#include <string.h>#include <math.h>#include <queue>using namespace std;int main(){    int p[9][9];    char c1, c2, c3, c4;    while (scanf("%c%c %c%c", &c1, &c2, &c3, &c4)!=EOF)    {memset(p, 0, sizeof(p));             /*不仅表示此处是否走过,而且可用来表示步数加一*/int a=c1-'a'+1, b=c2-'0', x=c3-'a'+1, y=c4-'0';p[a][b]=1;                           /*0表示走过,非0表示没走过*/queue<int> q;q.push(a);q.push(b);while (!q.empty()) {a = q.front();q.pop();b = q.front();q.pop();if (a==x&&b==y)break;if (a+1<=8){if (b+2<=8&&p[a+1][b+2]==0){p[a+1][b+2]=p[a][b]+1;q.push(a+1);q.push(b+2);}if (b-2>=1&&p[a+1][b-2]==0){p[a+1][b-2]=p[a][b]+1;q.push(a+1);q.push(b-2);}}if (a-1>=1){if (b+2<=8&&p[a-1][b+2]==0){p[a-1][b+2]=p[a][b]+1;q.push(a-1);q.push(b+2);}if (b-2>=1&&p[a-1][b-2]==0){p[a-1][b-2]=p[a][b]+1;q.push(a-1);q.push(b-2);}}if (a+2<=8){if (b+1<=8&&p[a+2][b+1]==0){p[a+2][b+1]=p[a][b]+1;q.push(a+2);q.push(b+1);}if (b-1>=1&&p[a+2][b-1]==0){p[a+2][b-1]=p[a][b]+1;q.push(a+2);q.push(b-1);}}if (a-2>=1){if (b+1<=8&&p[a-2][b+1]==0){p[a-2][b+1]=p[a][b]+1;q.push(a-2);q.push(b+1);}if (b-1>=1&&p[a-2][b-1]==0){p[a-2][b-1]=p[a][b]+1;q.push(a-2);q.push(b-1);}}}printf("To get from %c%c to %c%c takes %d knight moves.\n",c1, c2, c3, c4, p[a][b]-1);getchar();}return 0;}


 

原创粉丝点击