习题6-4 骑士的移动(Knight Moves, UVa 439)

裸的bfs。。。
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
#define LL long long
#define maxn 15
#define maxm 200005
#define mod 1000000007
#define INF 1000000007
#define eps 1e-5
#define PI 3.1415926535898
#define N 26
using namespace std;
//-------------------------CHC------------------------------//
typedef pair pii;
int d[maxn][maxn];
int dx[] = { 2, 1, -2, -1, 2, 1, -2, -1 };
int dy[] = { 1, 2, -1, -2, -1, -2, 1, 2 };

bool inside(pii p) {
	return p.first >= 1 && p.first <= 8 && p.second >= 1 && p.second <= 8;
}

int bfs(pii s, pii t) {
	CLEAR(d, -1);
	queue q;
	q.push(s);
	d[s.first][s.second] = 0;

	while (q.size()) {
		pii u = q.front(); q.pop();
		if (u == t) return d[u.first][u.second];
		for (int i = 0; i < 8; ++i) {
			pii v(u.first + dx[i], u.second + dy[i]);
			if (inside(v) && d[v.first][v.second] == -1) {
				d[v.first][v.second] = d[u.first][u.second] + 1;
				q.push(v);
			}
		}
	}
}

int main() {
	char x[3], y[3];
	while (~scanf("%s%s", &x, &y)) {
		pii s(x[0] - 'a' + 1, x[1] - '0'), t(y[0] - 'a' + 1, y[1] - '0');
		printf("To get from %s to %s takes %d knight moves.\n", x, y, bfs(s, t));
	}
	return 0;
}

你可能感兴趣的:(紫书,第六章,习题)