E.Barareh on Fire(暴力bfs)

本文介绍了一种算法,用于解决在虚拟环境中躲避蔓延的火灾,找到从起点到终点的最短安全路径。考虑到火势蔓延速度和人物移动能力,通过广度优先搜索(BFS)策略,确保角色避开火势,安全抵达目的地。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Barareh on Fire

The Barareh village is on fire due to the attack of the virtual enemy. Several places are already on fire and the fire is spreading fast to other places. Khorzookhan who is the only person remaining alive in the war with the virtual enemy, tries to rescue himself by reaching to the only helicopter in the Barareh villiage. Suppose the Barareh village is represented by an n × m grid. At the initial time, some grid cells are on fire. If a cell catches fire at time x, all its 8 vertex-neighboring cells will catch fire at time x + k. If a cell catches fire, it will be on fire forever. At the initial time, Khorzookhan stands at cell s and the helicopter is located at cell t. At any time x, Khorzookhan can move from its current cell to one of four edge-neighboring cells, located at the left, right, top, or bottom of its current cell if that cell is not on fire at time x + 1. Note that each move takes one second. Your task is to write a program to find the shortest path from s to t avoiding fire.

Input
There are multiple test cases in the input. The first line of each test case contains three positive integers n, m and k (1 ⩽ n,m,k ⩽ 100), where n and m indicate the size of the test case grid n × m, and k denotes the growth rate of fire. The next n lines, each contains a string of length m, where the jth character of the ith line represents the cell (i, j) of the grid. Cells which are on fire at time 0, are presented by character “f”. There may exist no “f” in the test case. The helicopter and Khorzookhan are located at cells presented by “t” and “s”, respectively. Other cells are filled by “-” characters. The input terminates with a line containing “0 0 0” which should not be processed.

Output
For each test case, output a line containing the shortest time to reach t from s avoiding fire. If it is impossible to reach t from s, write “Impossible” in the output.
在这里插入图片描述
Sample Output
4
Impossible
Impossible
1


题目大意是这样的,给你一个起点和终点,并给你很多火,你从起点出发到终点,你只能上下左右走,一步一秒,而每把火是k秒蔓延一次,每一次蔓延会使得周围8个格子无法走,问你能否安全到达终点,若能就输出最小步数,否则输出Impossible。
emmm,当时想太多了,一直以为暴力会超时,然后就一直用逆向bfs求出到每个火的最短时间。。。这个想法的漏洞太大就不多说了,最后实在没有办法了,用暴力枚举了一遍每一个顶点500ms+,(本来应该是一血的,结果被推后了2小时才A了,中间还WA了3发,真的是坑队友。。。)
这道题跑出来的时间各有差异,慢点的有2秒的,快一点的有12ms的,这里说一下中等的算法,bfs每一个火的时候记录该火到每一个点的时间,下一次bfs时如果另一个火到改点的时间大于等于已经放入的值,则该状态不加入队列(这样就大大缩短了时间),最后对人进行单独的bfs,在此过程中若到达一个点的时间大于等于该店已存在的值,不加入队列。
另外12ms的做法就是将所有的火先压入队列进行一次bfs操作就好了,500ms+的代码如下:

#include <cstdio>
#include <cstring>
#include <queue>
#define BYJ(a,b,n,m) (a>=1&&a<=n&&b>=1&&b<=m)
using namespace std;
char s[150][150];
int a[150][150],v[150][150],dis[150][150],k,n,m;
int dx[]= {-1,-1,-1,0,0,1,1,1},dy[]= {-1,0,1,-1,1,-1,0,1};
int dx1[]= {-1,0,0,1},dy1[]= {0,-1,1,0};
void bfs(int x,int y) {
	queue<int>qx,qy,fp;
	memset(v,0,sizeof(v));
	qx.push(x),qy.push(y),fp.push(0);
	v[x][y]=1;
	dis[x][y]=0;
	int bu,mark,bf=0;
	while (!qx.empty()) {
		for (int i=0; i<8; i++) {
			int xx=qx.front()+dx[i],yy=qy.front()+dy[i],sk2=fp.front()+k;
			if (BYJ(xx,yy,n,m) && !v[xx][yy] && sk2<dis[xx][yy]) {
				dis[xx][yy]=sk2;
				qx.push(xx),qy.push(yy),fp.push(sk2);
			}
			v[xx][yy]=1;
		}
		qx.pop(),qy.pop(),fp.pop();
	}
}
int main() {
	int sx,sy,fx,fy;
	while (scanf ("%d%d%d",&n,&m,&k)) {
		if (!n && !m && !k) break;
		int num=0;
		memset(v,0,sizeof(v));
		memset(a,0,sizeof(a));
		for (int i=1; i<=n; i++)
			for (int j=1; j<=m; j++)
				dis[i][j]=99999999;
		for (int i=1; i<=n; i++)
			scanf ("%s",s[i]+1);
		for (int i=1; i<=n; i++)
			for (int j=1; j<=m; j++) {
				if (s[i][j]=='f') a[i][j]=1,num++;
				else if (s[i][j]=='s') sx=i,sy=j;
				else if (s[i][j]=='t') fx=i,fy=j;
			}
		if (a[fx][fy] || a[sx][sy]) {
			printf ("Impossible\n");
			continue;
		}
		if (num) {
			for (int i=1; i<=n; i++)
				for (int j=1; j<=m; j++) {
					if (a[i][j]) {
						bfs(i,j);
					}
				}
		}
		queue<int>qqx,qqy,qstp;
		qqx.push(sx),qqy.push(sy),qstp.push(0);
		memset(v,0,sizeof(v));
		v[sx][sy]=1;
		int bu=0,mark=0;
		while (!qqx.empty()) {
			for (int i=0; i<4; i++) {
				int xx=qqx.front()+dx1[i],yy=qqy.front()+dy1[i],sk=qstp.front()+1;
				if (BYJ(xx,yy,n,m) && !v[xx][yy] && sk<dis[xx][yy]) {
					v[xx][yy]=1;
					if (xx==fx && yy==fy) {
						bu=sk;
						mark=1;
						break;
					}
					qqx.push(xx),qqy.push(yy),qstp.push(sk);
				}
			}
			if (mark) break;
			qqx.pop(),qqy.pop(),qstp.pop();
		}
		if (!num) printf ("%d\n",bu);
		else {
			if (dis[fx][fy]<=bu || !mark) printf ("Impossible\n");
			else printf ("%d\n",bu);
		}
	}
	return 0;
}

### 广度优先搜索(BFS暴力解法的实现 广度优先搜索(BFS)是一种经典的图遍历算法,通常用于解决最短路径问题或其他需要逐层扩展的情况。当提到“暴力解法”时,意味着通过穷举所有可能的状态来解决问题,而不考虑任何剪枝或优化策略。 以下是基于 BFS暴力解法的核心思路及其 Python 实现: #### 核心思想 1. **状态表示**:将问题中的每一种可能性视为一个节点。 2. **队列操作**:利用队列存储当前待处理的状态,并按照先进先出的原则逐一展开。 3. **终止条件**:一旦找到目标状态,则立即返回结果;如果无法达到目标状态,则继续直到队列为空。 4. **去重机制**:为了避免重复访问相同状态而导致死循环,需维护已访问过的集合。 #### 伪代码描述 ```python from collections import deque def bfs_violent(start, is_goal, get_neighbors): queue = deque([(start, 0)]) # 初始化队列 (当前状态, 步数) visited = set([start]) # 记录已经访问过状态 while queue: current_state, steps = queue.popleft() # 取出队首元素 if is_goal(current_state): # 判断是否到达目标状态 return steps # 返回所需步数 for neighbor in get_neighbors(current_state): # 遍历邻居节点 if neighbor not in visited: # 如果未被访问 visited.add(neighbor) # 添加到已访问集合 queue.append((neighbor, steps + 1)) # 加入队列并增加一步 return -1 # 若无解则返回-1 ``` 此通用框架适用于多种场景下的 BFS 暴力求解过程[^1]。 #### 应用实例 —— 数字拼图问题 假设我们有一个简单的数字拼图问题,其中空白格可以通过上下左右移动与其他数字互换位置,最终目的是恢复初始排列至标准顺序。这里给出具体编码方式如下所示: ```python def sliding_puzzle(board): m, n = len(board), len(board[0]) def board_to_tuple(bd): """ 将二维数组转换为一维元组 """ return tuple(cell for row in bd for cell in row) start = board_to_tuple(board) target = tuple(range(1,m*n)+[0]) zero_index_start = start.index(0) zero_index_target = target.index(0) directions = { 'up': (-n,), 'down': (+n,), 'left': (-1,) if zero_index_start % n != 0 else (), 'right':(+1,)if zero_index_start%n!=(n-1)else() } def neighbors(state): idx_zero=state.index(0) res=[] for d in directions.values(): new_idx=idx_zero+d[0] if 0<=new_idx<m*n: list_s=list(state) list_s[idx_zero],list_s[new_idx]=list_s[new_idx],list_s[idx_zero] res.append(tuple(list_s)) return res from collections import deque q=deque([(start,zero_index_start,0)]) seen={start} while q: state,idx_zero,dist=q.popleft() if state==target:return dist for nei in neighbors(state): if nei not in seen: seen.add(nei) q.append((nei,nei.index(0),dist+1)) return -1 ``` 上述程序展示了如何运用 BFS 来解答滑动谜题类题目,它体现了从单一源头出发逐步探索直至发现解决方案的过程[^2]。 #### 多源 BFS 扩展讨论 相较于单源 BFS,多源 BFS 主要差异在于起始阶段会把多个潜在起点一同加入队列之中,从而使得整个搜索流程能够更加高效地覆盖更大范围内的候选区域[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值