hdu 1372 bfs 计算起点到终点的距离

#include <cstdio>
#include <iostream>
#include <queue>

using namespace std;

int dir[8][2]={{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{-2,1},{2,-1},{-2,-1}};

int vis[9][9];

int sx,sy,ex,ey;

struct node
{
	int x,y,step;
};

int num;

queue<node> q;

 void bfs(int x1,int y1)
 {
     int i;
     while(!q.empty()) q.pop();
     node cur,next;
     cur.x=x1;
     cur.y=y1;
	 cur.step=0;
     q.push(cur);
     memset(vis,0,sizeof(vis));
     vis[x1][y1]=1;
     while(!q.empty())
     {
         cur=q.front();
         q.pop();
		 //printf("%d %d %d %d %d\n",cur.x,cur.y,num,ex,ey);
		 if(cur.x==ex&&cur.y==ey)
		 {
			 num=cur.step;
			 return ;
		 }
		 //printf("%d %d %d\n",cur.x,cur.y,num);
         for(i=0;i<8;i++)
         {
             next.x=cur.x+dir[i][0];
             next.y=cur.y+dir[i][1];
			 next.step=cur.step+1;
             if(next.x<1 || next.x>8 || next.y<1 || next.y>8 ||vis[next.x][next.y]) continue;
             vis[next.x][next.y]=1;
             q.push(next);
         }
     }
 }

int main()
{
	char s[6];

	while(gets(s))
	{
		sy=s[0]-'a'+1;

		sx=s[1]-'0';

		ey=s[3]-'a'+1;

		ex=s[4]-'0';

		//printf("%d %d %d %d\n",sx,sy,ex,ey);

		bfs(sx,sy);

		printf("To get from %c%c to %c%c takes %d knight moves.\n",s[0],s[1],s[3],s[4],num);
	}

	return 0;
}

  

posted @ 2012-06-04 14:04  shijiwomen  阅读(225)  评论(0编辑  收藏  举报