bfs 的题目
http://acm.hdu.edu.cn/showproblem.php?pid=1372
题目简述:一个8*8的棋盘,输入两点,求马从第一点到第二点所需要的最少步数
Input
e2 e4
a1 b2
b2 c3
Output
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
代码:
#include<iostream>
#include<queue>
using namespace std;
int map[10][10];
int dir[8][2]={-2,-1,-1,-2,1,-2,2,-1,-2,1,-1,2,1,2,2,1};
int sx,sy,ex,ey;
struct node
{
int x,y;
int step;
};
bool cmp(int x,int y)
{
if(x>=0&&x<8&&y>=0&&y<8&&map[x][y]==0)
return 1;
return 0;
}
int bfs()
{
queue<node>q;
node cur,next;
int i,j;
cur.x=sx;
cur.y=sy;
cur.step=0;
map[sx][sy]=1;
q.push(cur);
while(!q.empty())
{
cur=q.front();
if(cur.x==ex&&cur.y==ey) return cur.step;
q.pop();
for(i=0;i<8;i++)
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
if(cmp(next.x,next.y))
{
next.step=cur.step+1;
map[next.x][next.y]=1;
q.push(next);
}
}
}
return 0;
}
int main()
{
char c1,e1,c2,e2;
while(scanf("%c%c %c%c",&c1,&e1,&c2,&e2)!=EOF)
{
memset(map,0,sizeof(map));
sx=c1-'a';
sy=e1-'1';
ex=c2-'a';
ey=e2-'1';
// cout<<sx<<' '<<sy<<' '<<ex<<' '<<ey<<' ';
int ans=bfs();
printf("To get from %c%c to %c%c takes %d knight moves.\n",c1,e1,c2,e2,ans);
getchar();
}
return 0;
}
浙公网安备 33010602011771号