您的位置:首页 > 其它

UVa 439 Knight Moves——bfs

2017-06-10 21:30 323 查看
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

int G[10][10], sx, sy, ex, ey;
struct Node {
int x, y, step;
}node;

bool edge(int x, int y) {
if (0 <= x && x < 8 && 0 <= y && y < 8) return true;
else return false;
}

int bfs() {
queue<Node> q;
q.push((Node){sx, sy, 0});

while (!q.empty()) {
node = q.front(); q.pop();
if (node.x == ex && node.y == ey) return node.step;
if (edge(node.x - 2, node.y + 1)) q.push((Node){node.x-2, node.y+1, node.step+1});
if (edge(node.x - 1, node.y + 2)) q.push((Node){node.x-1, node.y+2, node.step+1});
if (edge(node.x + 1, node.y + 2)) q.push((Node){node.x+1, node.y+2, node.step+1});
if (edge(node.x + 2, node.y + 1)) q.push((Node){node.x+2, node.y+1, node.step+1});
if (edge(node.x + 2, node.y - 1)) q.push((Node){node.x+2, node.y-1, node.step+1});
if (edge(node.x + 1, node.y - 2)) q.push((Node){node.x+1, node.y-2, node.step+1});
if (edge(node.x - 1, node.y - 2)) q.push((Node){node.x-1, node.y-2, node.step+1});
if (edge(node.x - 2, node.y - 1)) q.push((Node){node.x-2, node.y-1, node.step+1});
}
}

int main()
{
string temp1, temp2;
while (cin >> temp1 >> temp2) {
sx = 8 - temp1[1] + '0';
sy = temp1[0] - 'a';
ex = 8 - temp2[1] + '0';
ey = temp2[0] - 'a';
cout << "To get from "<<temp1<<" to "<<temp2<<" takes "<<bfs()<<" knight moves." << endl;

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: