UVa 439骑士的移动(BFS)

时间:2023-01-11 12:33:44

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=380

做了这道题之后对BFS总算是有了点认识了。

 #include<iostream>
#include<cstring>
using namespace std; int map[][];
typedef struct node
{
int x, y, z;
node(int a, int b, int c) { x = a; y = b; z = c; }
node() {}
}queue; queue q[]; int d[][] = { { , }, { , - }, { -, - }, { -, }, { , }, { , - }, { -, }, { -, - } };
int bfs(int x1, int y1, int x2, int y2)
{
int move = , number = ;
if (x1 == x2 && y1 == y2) return ;
memset(map, , sizeof(map));
q[] = node(x1, y1, );
while (move < number)
{
queue p = q[move++];
for (int k = ; k < ; k++)
{
int xx = p.x + d[k][];
int yy= p.y + d[k][];
if (xx == x2 && yy == y2) return p.z + ;
if (!map[xx][yy] && xx> && xx< && yy> && yy < )
{
map[xx][yy] = ;
q[number++] = node(xx, yy, p.z + );
}
}
}
} int main()
{
char s1, s2;
int x1, x2, y1, y2;
while (cin >> s1 >> y1 >> s2 >> y2)
{
x1 = (int)(s1 - 'a' + );
x2 = (int)(s2 - 'a' + );
int x=bfs(x1, y1, x2, y2);
cout << "To get from "<<s1<<y1<< " to " <<s2<<y2<< " takes "<<x <<" knight moves."<< endl;
}
return ;
}