hduoj_1242(bfs)

#include 

int r, c;
char map[201][201];
char time[201][201];

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

struct node {
	int x, y;
}q[100000];

int fx, fy;
int ax, ay;

void bfs()
{
	int head, tail;

	int tx, ty, t_time;

	int i;
	
	// 初始化队列
	head = 0;
	tail = 1;

	q[1].x = fx;
	q[1].y = fy;

	while (head < tail)
	{
		head++;
		
		for (i = 0; i < 4; i++)
		{
			tx = q[head].x + dx[i];
			ty = q[head].y + dy[i];

			t_time = time[q[head].x][q[head].y] + 1;

			if (tx > 0 && ty > 0 && tx <= r&&ty <= c&&map[tx][ty] != '#')
			{
				if (map[tx][ty] == 'x')
				{
					t_time++;
				}

				if (-1 == time[tx][ty] || t_time < time[tx][ty])
				{
					time[tx][ty] = t_time;
					tail++;
					q[tail].x = tx;
					q[tail].y = ty;
				}
			}
 		}
	}
}

int main()
{
	int i, j;
	while (EOF != scanf("%d %d", &r, &c) && (r || c))
	{
		getchar();
		for (i = 1; i <= r; i++)
		{
			for (j = 1; j <= c; j++)
			{ 
				scanf("%c", &map[i][j]);

				time[i][j] = -1;               // 还没到过
				if (map[i][j] == 'a')
				{
					ax = i;
					ay = j;
				}
				if (map[i][j] == 'r')
				{
					fx = i;
					fy = j;
					time[i][j] = 0;
				}
			}
			getchar();
		}

		bfs();

		if (-1 == time[ax][ay])
		{
			printf("Poor ANGEL has to stay in the prison all his life.\n");
		}
		else
		{
			printf("%d\n", time[ax][ay]);
		}		
	}
}

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