HDU1372 Knight Moves(BFS)

来源:互联网 发布:网络监测工具 编辑:程序博客网 时间:2024/06/05 08:49

做的第一道BFS,和DFS差不多,是有差不多的模板的,基本上每道题的写法都差不多,有时间的话会在博客里写一些模板的东西

#include<iostream>#include<string.h>#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};int map[10][10],a,b;char str1[2],str2[2];struct node{int x,y,s;};int bfs(){queue<node> Q;node t,q,p;t.x = str1[0]-'a';t.y = str1[1]-'1';t.s = 0;memset(map,0,sizeof(map)); map[t.x][t.y] = 1;Q.push(t);while(!Q.empty()){q = Q.front();Q.pop();if(q.x == (str2[0]-'a') && q.y == (str2[1]-'1'))return q.s;for(int i = 0;i<8;i++){p.x = q.x + dir[i][0];p.y = q.y + dir[i][1];if(p.x == (str2[0]-'a') && p.y == (str2[1]-'1'))return q.s+1;if(p.x>=0 && p.x<8 && p.y>=0 && p.y<8 && map[p.x][p.y] == 0){p.s = q.s+1;map[p.x][p.y] = 1;Q.push(p);}}}}int main(){while(~scanf("%s %s",&str1,&str2)){printf("To get from %s to %s takes %d knight moves.\n",str1,str2,bfs());}return 0;}


0 0
原创粉丝点击