马走日原题链接
题目描述:
思路:
BFS,借用二维数组使用for循环遍历八种情况,这样就不用一个一个写了
AC代码:
#include <iostream>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
struct node
{
int x, y;
int steps;
}now,nex,target;
int m,n,step;
int vis[10][10];
int dir[8][2]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
char a1[10],a2[10];//记录目标点
void bfs()
{
queue<node> qu;
memset(vis,0,sizeof(vis));
now.x = a1[0] - 'a' +1;
now.y = a1[1] - '0';
now.steps = 0;
vis[now.x][now.y] = 1;
qu.push(now);
while(!qu.empty())
{
now = qu.front();
qu.pop();
if(now.x == m && now.y == n)
{
step = now.steps;
return;
}
for(int i = 0; i < 8; i++)
{
nex.x = now.x + dir[i][0];
nex.y = now.y + dir[i][1];
if(nex.x >=1 && nex.x<= 8 && nex.y >= 1 && nex.y <=8 && !vis[nex.x][nex.y])
{
vis[nex.x][nex.y] = 1;
nex.steps = now.steps + 1;
qu.push(nex);
}
}
}
}
int main()
{
while(scanf("%s %s",&a1,&a2) != EOF)
{
m = a2[0] -'a' +1;
n = a2[1] - '0';
bfs();
printf("To get from %s to %s takes %d knight moves.\n",a1, a2, step);
}
}