ZOJ 1091 Knight Moves 【BFS】

//2633055 	2011-08-19 21:45:58 	Accepted 	1091 	C 	10 	160 	ylwh@Unknown
#include <stdio.h>
#include <string.h>
#define N 9
int main()
{
	int map[N][N], x1, y1, x2, y2, i, j, Q[N*N][2], head, tail, nowx, nowy, dx, dy;
	int dxdy[][2] = { {2, 1}, {-2, 1}, {2, -1}, {-2, -1}, {1, 2}, {1, -2}, {-1, -2}, {-1, 2} };
	char ch1, ch2;
	while(scanf(" %c%d %c%d", &ch1, &x1, &ch2, &x2) != EOF)
	{
		y1 = ch1 - 'a';
		x1--;
		y2 = ch2 - 'a';
		x2--;
		head = 0;
		tail = 1;
		Q[head][0] = x1;
		Q[head][1] = y1;
		memset(map, 0, sizeof(map));
		map[x1][y1] = 1;
		while(head != tail)
		{
			nowx = Q[head][0];
			nowy = Q[head][1];
			for(i=0; i<8; i++)
			{
				dx = nowx + dxdy[i][0];
				dy = nowy + dxdy[i][1];
				if(dx >= 0 && dx < 8 && dy >= 0 && dy < 8 && map[dx][dy] == 0)
				{
					map[dx][dy] = map[nowx][nowy] + 1;
					Q[tail][0] = dx;
					Q[tail][1] = dy;
					tail = (tail + 1) % (N * N);
					if(dx == x2 && dy == y2)
						goto X;
				}
			}
			head = (head + 1) % (N * N);
		}
		X:
		printf("To get from %c%d to %c%d takes %d knight moves.\n", ch1, x1+1, ch2, x2+1, map[x2][y2] - 1);
	}
    return 0;
}


你可能感兴趣的:(ZOJ 1091 Knight Moves 【BFS】)