UVa 11624 Fire!(起火迷宫)

题目链接:UVa 11624

题意:

迷宫中有着火点,每次向四周扩散(墙不会被点燃),问能否逃出?若逃出需几步?

分析:

一开始是想用bfs先记录下着火的顺序,也就是可走的方格在哪一步被点着,然后在用bfs找最短路径时多个判断即可。可是这样就TLE了,然后就废了好大劲,将两个bfs合并了,难点就是return条件判断和“剪枝”。从早上做到现在,终于AC了!


CODE:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const int maxn = 1005;
int dir[4][2] = { {-1,0},{0,-1},{1,0},{0,1} };
int R, C, T, ans, jx, jy, fx, fy;
int wall[maxn][maxn];
char s[maxn], a[maxn][maxn];
int vis[maxn][maxn];
int escapex, escapey, firex, firey;
int fire[maxn][maxn];

int valid(int x, int y)
{
	if (x < 0 || y < 0 || x == R || y == C || wall[x][y]) return 0;
	return 1;
}

struct Node {
	int step, x, y;
	int isfire;
}cur, nextnode;

int bfs()
{
	queue q;
	memset(vis, 0, sizeof(vis));
	memset(fire, 0, sizeof(fire));
	for (int i = 0;i < R;i++)
	{
		for (int j = 0;j < C;j++)
		{
			if (a[i][j] == 'F')
			{
				cur.x = i;
				cur.y = j;
				cur.step = 0;
				cur.isfire = 1;
				fire[i][j] = 1;
				q.push(cur);//起火点先进队列
			}
		}
	}
	cur.x = jx;
	cur.y = jy;
	cur.step = 0;
	cur.isfire = 0;
	vis[jx][jy] = 1;
	q.push(cur);//人后进队列
	while (!q.empty())
	{
		cur = q.front();
		q.pop();
		if (cur.isfire)
		{
			for (int i = 0;i < 4;i++)
			{
				firex = cur.x + dir[i][0];
				firey = cur.y + dir[i][1];
				if (!valid(firex, firey) || fire[firex][firey]) continue;//fire[i][j]:坐标(i,j)已着火
				nextnode.step = cur.step + 1;
				nextnode.x = firex;
				nextnode.y = firey;
				nextnode.isfire = 1;
				fire[firex][firey] = 1;
				q.push(nextnode);
			}
		}
		else
		{
			for (int i = 0;i < 4;i++)
			{
				escapex = cur.x + dir[i][0];
				escapey = cur.y + dir[i][1];
				nextnode.step = cur.step + 1;
				nextnode.x = escapex;
				nextnode.y = escapey;
				nextnode.isfire = 0;
				if (nextnode.x == -1 || nextnode.x == R || nextnode.y == -1 || nextnode.y == C)
					return nextnode.step;
				if (!valid(escapex,escapey)|| vis[escapex][escapey] || fire[escapex][escapey]) continue;
				vis[escapex][escapey] = 1;
				q.push(nextnode);
			}
		}
	}
	return -1;
}

int main()
{
#ifdef LOCAL 
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
#endif
	cin >> T;
	while (T--)
	{
		cin >> R >> C;
		memset(wall, 0, sizeof(wall));
		for (int i = 0;i < R;i++)
		{
			scanf("%s", s);
			for (int j = 0;j < C;j++)
			{
				a[i][j] = s[j];
				if (s[j] == '#') wall[i][j] = 1;
				else if (s[j] == 'J')
				{
					jx = i;
					jy = j;
				}
			}
		}
		ans = bfs();
		if (ans == -1) printf("IMPOSSIBLE\n");
		else printf("%d\n", ans );
	}
	return 0;
}


你可能感兴趣的:(广度优先搜索(BFS))