hdu 1372——Knight Moves(BFS)

来源:互联网 发布:2016年网络手游排行榜 编辑:程序博客网 时间:2024/05/16 07:13

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1372

解题思路:比较基础的bfs。看题又是求最少步数,肯定广搜好做。初接触搜索,所以又学习了一下网上的代码...

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <queue>using namespace std;int vis[10][10]; //标记char s1[5],s2[5];int ex,ey,sx,sy; //起点和终点int dir[8][2]={1,2,2,1,1,-2,2,-1,-1,2,-2,1,-1,-2,-2,-1}; //马走“日”,8个方向struct node{int x,y;int step;};int check(int x,int y){if(x<1 || x>8 || y<1 || y>8)return 0;return 1;}int bfs(){int i;node now,next;queue<node>q;while(!q.empty())q.pop();memset(vis,0,sizeof(vis));now.x=sx;now.y=sy;now.step=0;q.push(now);vis[sx][sy]=1;while(!q.empty()){now=q.front();q.pop();if(now.x==ex && now.y==ey)return now.step;for(i=0;i<8;i++){next.x=now.x+dir[i][0];next.y=now.y+dir[i][1];next.step=now.step+1;if(check(next.x,next.y)==0)continue;if(!vis[next.x][next.y]){q.push(next);vis[next.x][next.y]=1;}}}return -1;}int main(){while(scanf("%s%s",s1,s2)!=EOF){sx=s1[0]-'a'+1;sy=s1[1]-'0';ex=s2[0]-'a'+1;ey=s2[1]-'0';printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs());}return 0;}


原创粉丝点击