习题6-4 骑士的移动 UVa439

1.题目描述:点击打开链接

2.解题思路:典型的BFS,当找到终点时break即可

3.代码:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<cassert>
#include<cstdlib>
#include<cstdio>
#include<ctime>
#include<cmath>
#include<cstring>
#include<functional>
using namespace std;
const int maxn = 9;
int vis[maxn][maxn];
const string buf = "abcdefgh";
typedef pair<int, int>Pair;
Pair d1, d2;
const int dx[] = { -2, -2, -1, -1, 1, 1, 2, 2 };
const int dy[] = { -1, 1, -2, 2, -2, 2, -1, 1 };
queue < Pair >q;
string s1, s2;
bool inside(int x, int y)
{
	if (x<0 || x>7 || y<0 || y>7)return false;
	return true;
}
void bfs()
{
	int flag = 0;
	int x2 = d2.first, y2 = d2.second;
	vis[d1.first][d1.second] = 0;
	if (d1 != d2)
	{
		q.push(d1);
		while (!q.empty())
		{
			Pair d = q.front(); q.pop();
			int x1 = d.first, y1 = d.second;
			for (int d = 0; d < 8; d++)
			{
				int i = x1 + dx[d], j = y1 + dy[d];
				if (inside(i, j) && vis[i][j] == -1)
				{
					vis[i][j] = vis[x1][y1] + 1;
					if (i == x2&&j == y2){ flag = 1; break; }
					q.push(Pair(i, j));
				}
			}
			if (flag)break;
		}
	}
	else flag = 1;
	if (flag)
		cout << "To get from " << s1 << " to " << s2 << " takes " << vis[x2][y2] << " knight moves.\n";
	while (!q.empty())q.pop();
}
int main()
{
	while (cin >> s1 >> s2)
	{
		memset(vis, -1, sizeof(vis));
		d1 = make_pair(8 - s1[1] + '0', buf.find(s1[0]));
		d2 = make_pair(8 - s2[1] + '0', buf.find(s2[0]));
		bfs();
	}
	return 0;
}




你可能感兴趣的:(uva)