#include <cstdio>
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <queue>
#include <cstring>
using namespace std;
int vis[100][100];
int dis[100][100];
int dx[8] = {1,2,2,1,-1,-2,-2,-1};
int dy[8] = {-2,-1,1,2,2,1,-1,-2};
int x[4];
typedef struct node{
int x, y;
}node;
queue<node> que;
bool judge(int x, int y)
{
if(x >= 1 && x <= 8 && y >= 1 && y <= 8)
return true;
else
return false;
}
void bfs()
{
memset(vis, 0, sizeof(vis));
memset(dis, 0, sizeof(dis));
node start;
start.x = x[0];
start.y = x[1];
vis[x[0]][x[1]] = 1;
while(!que.empty())
que.pop();
que.push(start);
while(!que.empty())
{
node front = que.front();
que.pop();
for(int i = 0; i < 8; i++)
{
int xx = front.x + dx[i];
int y = front.y + dy[i];
if(judge(xx, y) && !vis[xx][y])
{
node neww;
neww.x = xx;
neww.y = y;
vis[xx][y] = 1;
dis[xx][y] = dis[front.x][front.y] + 1;
if(xx == x[2] && y == x[3])
return ;
que.push(neww);
}
}
}
}
int main()
{
//freopen("ztest.txt","r",stdin);
string str;
while(getline(cin, str))
{
int u = 0;
for(int i = 0; i< str.size(); i++)
{
if(str[i] != ' ')
{
if(isalpha(str[i]))
x[u++] = str[i]-'a'+1;
else
x[u++] = str[i]-'0';
}
}
bfs();
printf("To get from %c%d to %c%d takes %d knight moves.\n",x[0]+'a'-1,x[1],x[2]+'a'-1,x[3],dis[x[2]][x[3]]);
}
return 0;
}
uva 439 bfs 广搜
最新推荐文章于 2020-04-08 21:33:07 发布