广搜
题意 :就是相当 中国的象棋 马走日 ;
首先建立一个图; 每次要进行初始化;
然后广搜;
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int map[10][10];
int dir[8][2] = {{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};
int a, b, m, n, flag;
struct node
{
int x, y;
int step;
};
void bfs(int x, int y)
{
queue<node>q;
node temp, type;
temp.x = x;
temp.y = y;
temp.step = 0;
map[x][y] = 1;
q.push(temp);
while(!q.empty())
{
temp = q.front();
q.pop();
if(temp.x == b && temp.y == n)
{
flag = temp.step;
return ;
}
for(int i = 0; i < 8; i++)
{
int fx = temp.x + dir[i][0];
int fy = temp.y + dir[i][1];
if(fx > 0 && fx <= 8 && fy > 0 && fy <= 8 && map[fx][fy] == 0)
{
type.x = fx;
type.y = fy;
type.step = temp.step + 1;
map[fx][fy] = 1;
q.push(type);
}
}
}
return ;
}
int main()
{
string ch1, ch2;
while(cin >> ch1 >> ch2)
{
a = ch1[1] - '0';
b = ch2[1] - '0';
m = ch1[0] - 'a' + 1;
n = ch2[0] - 'a' + 1;
memset(map, 0, sizeof(map));
flag = 0;
bfs(a, m);
cout << "To get from "<< ch1 << " to "<< ch2 << " takes " << flag << " knight moves." << endl;
//printf("%s%s%d\n", ch1, ch2, flag);
}
}
hdu1372
最新推荐文章于 2021-07-28 16:43:31 发布