题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=91

本来说好好研究一下广搜,然后告诉那哥们,结果没找到机会,然后还没告诉便用上了,刚刚看了下,光搜上也没写些什么,想想还是写点以便自己理解,希望对别人也有所帮助;

有时候人悲剧的时候那也没办法,在比赛的时候2道题出现细节性错误,结果一同over,我表示鸭梨很大,回去后一遍通过又是为何?

我不得而知:

View Code
#include<stdio.h>
#include<string.h>
#include<queue> ////这里用的队列来处理
using namespace std;
int flag[10][10]; ///共8*8个,这里用来标记是否被用过,注意flag[][]==1表示用过
int s_x,s_y,e_x,e_y; ////s表示起点,e表示终点
int dir[8][2]={2,-1,1,-2,-1,-2,-2,-1,-2,1,-1,2,1,2,2,1};////在某点有8个方向走
typedef struct node
{
int x,y,step; ////x,y依然表示位置,step表示步数,尽量键明旨意
}node; ////
node cur,next;

int BFS(int x,int y)
{
int i;
cur.x=x;
cur.y=y;
cur.step=0;
if(cur.x==e_x&&cur.y==e_y) ////这里表示起止位置相同
{
return 0;
}
queue<node>qu; ////建立新队列
qu.push(cur); //////////入队
while(!qu.empty()) ///判断队列是否为空
{
cur=qu.front(); ///取队列首
qu.pop(); ///删除队列首
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==e_x&&next.y==e_y) ////找到终点
{
return next.step;
}
if(next.x>0&&next.x<9&&next.y>0&&next.y<9&&flag[next.x][next.y]==0)
{
flag[next.x][next.y]=1;
qu.push(next); ///入队
}
}
}
}

int main()
{
char str[4];
char str2[4];
while(scanf("%s",str)!=EOF)
{
getchar();
memset(flag,0,sizeof(flag));
gets(str2);
s_x=(str[0]-'a'+1);
s_y=(str[1]-'0');
e_x=(str2[0]-'a'+1);
e_y=(str2[1]-'0');
flag[s_x][s_y]=1; //比赛时我是在这里被K了
printf("To get from %s to %s takes %d knight moves.\n",str,str2,BFS(s_x,s_y));
}
return 0;
}


 

posted on 2012-03-26 19:23  world_ding  阅读(885)  评论(0编辑  收藏  举报