hduoj_1175(bfs)

#include 
#include 
#include 

int dx[] = { 0,0,1,-1 };
int dy[] = { -1,1,0,0 };

int n, m;
int x1, y1, x2, y2;
int flag;

int map[1001][1001];
int map_b[1001][1001];

struct node {
	int x, y;
	int now_d, count_d;
}q[1000000];


void bfs()
{
	// -1 have arrived
	int i;
	int head, tail;
	int tx, ty;
	int count_d;

	head = 0;
	tail = 1;

	q[1].x = x1;
	q[1].y = y1;
	q[1].count_d = 0;
	q[1].now_d = -1;

	map[x1][y1] = -1;        // have arrived

	while (head < tail)
	{
		head++;
		for (i = 0; i < 4; i++)
		{
			if (q[head].now_d == -1 || q[head].now_d != i)
			{
				count_d = q[head].count_d + 1;
				if (count_d > 3) continue;
			}
			else
			{
				count_d = q[head].count_d;
			}

			tx = q[head].x + dx[i];
			ty = q[head].y + dy[i];

			if (tx == x2 && ty == y2)
			{
				flag = 1;
				return;
			}

			if (tx > 0 && ty > 0 && tx <= n&&ty <= m && 0 == map[tx][ty])
			{
				tail++;
				map[tx][ty] = -1;
				q[tail].x = tx;
				q[tail].y = ty;
				q[tail].now_d = i;
				q[tail].count_d = count_d;
			}
		}
	}
}

int main()
{
	int i, j;
	int k;

	while (EOF != scanf("%d %d", &n, &m) && (n || m))
	{
		for (i = 1; i <= n; i++)
		{
			for (j = 1; j <= m; j++)
			{
				scanf("%d", &map_b[i][j]);
			}
		}

		scanf("%d", &k);

		for (i = 1; i <= k; i++)
		{
			memcpy(map, map_b, sizeof(map_b));

			scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
			
			flag = 0;

			if (map[x1][y1] != map[x2][y2] || !map[x1][y1] || !map[x2][y2])
			{
				printf("NO\n");
				continue;
			}

			bfs();

			if (flag) printf("YES\n");
			else printf("NO\n");
		}
		
	}
	return 0;
}

你可能感兴趣的:(算法)