DFS和BFS易错点记录——POJ 3669Meteor Shower

本文记录了在解决Meteor Shower问题时,使用DFS和BFS算法需要注意的错误点,即在插入队列后必须立即判断重复,否则可能导致超时。Bessie需要在流星撞击地球时找到安全位置,避免被撞击。问题涉及到二维平面上的路径规划和时间优化。

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

记录一下错误点:判重必须立即判重,而不是等到使用的时候再判重

刚刷了一道题,一直超时,找了很久bug才找到

在BFS中,插入队列后就必须立即判重,如果在退出队列后再判重,期间会有很多次重复插入,导致超时,DFS同理

 

Meteor Shower

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 6878 Accepted: 2001

Description

Bessie hears that an extraordinary meteor shower is coming; reports say that these meteors will crash into earth and destroy anything they hit. Anxious for her safety, she vows to find her way to a safe location (one that is never destroyed by a meteor) . She is currently grazing at the origin in the coordinate plane and wants to move to a new, safer location while avoiding being destroyed by meteors along her way.

The reports say that M meteors (1 ≤ M ≤ 50,000) will strike, with meteor i will striking point (XiYi) (0 ≤ Xi ≤ 300; 0 ≤ Yi ≤ 300) at time Ti (0 ≤ Ti  ≤ 1,000). Each meteor destroys the point that it strikes and also the four rectilinearly adjacent lattice points.

Bessie leaves the origin at time 0 and can travel in the first quadrant and parallel to the axes at the rate of one distance unit per second to any of the (often 4) adjacent rectilinear points that are not yet destroyed by a meteor. She cannot be located on a point at any time greater than or equal to the time it is destroyed).

Determine the minimum time it takes Bessie to get to a safe place.

Input

* Line 1: A single integer: M
* Lines 2..M+1: Line i+1 contains three space-separated integers: XiYi, and Ti

Output

* Line 1: The minimum time it takes Bessie to get to a safe place or -1 if it is impossible.

Sample Input

4
0 0 2
2 1 2
1 1 2
0 3 5

Sample Output

5

附上AC代码:

#include <cstdio>  
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <stack>
#include <queue>
using namespace std;
#define ll long long
int m;
int mapp[350][350];
int dx[] = {-1,1,0,0,0};
int dy[] = {0,0,-1,1,0};
struct M
{
	int x,y,t;
}met[50005];
bool cmp(M one,M two)
{
	return one.t < two.t;
}
int bfs()
{
	queue<M> q;
	M m;
	m.x = 0;
	m.y = 0;
	m.t = 0;
	q.push(m);
	while(!q.empty())
	{
		M m = q.front();
		q.pop();
		//cout << m.x << ' '<< m.y << ' '<< m.t<<endl;
		if(mapp[m.x][m.y] == -1)
			return m.t;
		for(int i = 0;i <= 3;i++)
		{
			M mm = m;
			mm.x+=dx[i];
			mm.y+=dy[i];
			mm.t++;
			if(mm.x >= 340 || mm.y >= 340 || mm.x < 0 || mm.y < 0)
				continue;
			else if(mapp[mm.x][mm.y] == -1 || mapp[mm.x][mm.y] > mm.t)
			{
				q.push(mm);
				if(mapp[mm.x][mm.y] != -1)
					mapp[mm.x][mm.y] = 0;//这个加入队列的时候就必须修改来判重,否则如果出队列再判重,这期间可能会再有很多次重复插入
			}
		}
	}
	return -1;
}
int main()
{
	while(cin >> m)
	{
		memset(mapp,-1,sizeof(mapp));
		for(int i = 0;i < m;i++)
			scanf("%d%d%d",&met[i].x,&met[i].y,&met[i].t);
		sort(met,met+m,cmp);
		for(int i = 0;i < m;i++)
			for(int j = 0;j <= 4;j++)
			{
				M temp = met[i];
				temp.x+=dx[j];
				temp.y+=dy[j];
				if(temp.x < 0 || temp.y < 0 || temp.x >= 340 || temp.y >= 340)
					continue;
				else if(mapp[temp.x][temp.y] == -1)
					mapp[temp.x][temp.y] = temp.t;
			}
		cout << bfs() <<endl;

	}
	//cout << "AC" <<endl;
	return 0;
}

 

<think>好的,我现在要帮用户解答关于学习DFSBFS时新手需要注意的易错。首先,我得回想自己当初学习这两个算法时遇到的问题,以及常见的学生困惑。 首先,DFSBFS都是图遍历的算法,但它们的实现方式应用场景不同。新手可能会混淆它们的适用情况。比如,DFS用栈或递归,BFS用队列,这需要强调。可能用户在学习时没有理解为什么选择不同的数据结构,导致实现误。 然后,递归的DFS容易导致栈溢出,特别是当图的深度很大时。这需要提醒用户注意递归深度,可能要考虑迭代实现或者设置递归限制。另外,访问标记的设置时机也很关键,比如在访问节后立即标记,避免重复访问,特别是在图中存在环的情况下。 对于BFS,队列的管理可能出,比如忘记标记节导致重复入队。比如,正确的做法是在节入队时立即标记,而不是出队时才标记,否则同一节可能被多次加入队列,影响效率甚至导致误。 接下来,终止条件的问题。DFS可能在找到目标后忘记及时返回,继续不必要的搜索。而BFS如果未正确处理队列为空的情况,可能导致误。比如,在寻找最短路径时,BFS通常更合适,但如果不正确处理队列,可能无法得到正确结果。 内存方面,BFS的空间复杂度在树中是O(宽度),而DFS是O(深度)。如果树很宽,BFS可能消耗更多内存,而DFS在深度大的情况下可能栈溢出。用户可能没有意识到这,导致程序崩溃。 路径记录也是一个问题。DFS回溯时需要恢复状态,而BFS可能需要记录前驱节来重建路径。新手可能不知道如何正确记录路径,或者在回溯时忘记恢复状态,导致结果误。 剪枝优化方面,DFS如果不做剪枝,效率会很低。比如在排列组合问题中,重复访问未剪枝会导致大量无效搜索。需要提醒用户学会剪枝技巧,比如使用访问数组或条件判断。 应用场景混淆也是一个常见问题。比如最短路径问题应该用BFS,而拓扑排序可能用DFSBFS。用户可能误地选择了算法,导致结果不正确或效率低下。 最后,用户可能需要具体的例子来理解这些易错,比如通过迷宫问题比较DFSBFS的不同,或者展示递归迭代实现的代码差异。这样他们可以更直观地理解问题所在。 总结一下,我需要分列出各个易错,并给出具体的解释建议,帮助用户避免常见误,同时对比DFSBFS的不同,强调它们的正确应用场景实现细节。</think>以下是学习DFS(深度优先搜索)BFS(广度优先搜索)时常见的易错及注意事项: --- ### **一、DFS易错** 1. **递归终止条件缺失** - 忘记设置递归出口或条件误,导致无限递归(最终栈溢出) - ✅ 始终先明确递归终止条件,例如 `if (已到达目标) return;` 2. **访问标记未及时更新** - 进入节后未立即标记为已访问,导致重复访问(尤其在存在环的图中) - ✅ 在访问节时立即标记(如 `visited[node] = true`) 3. **回溯逻辑误** - 需要回溯状态的问题(如排列组合)中,忘记恢复现场 - ✅ 在递归后重置状态: ```python path.append(node) # 记录路径 dfs(...) path.pop() # 回溯 ``` --- ### **二、BFS易错** 1. **队列初始化误** - 未将起始节加入队列,或未标记起始节为已访问 - ✅ 初始时:`queue = deque([start])` 并标记 `visited[start] = True` 2. **层序处理混淆** - 未按层处理节(如求最短路径时),导致结果误 - ✅ 使用分层BFS记录每层节数量): ```python while queue: level_size = len(queue) for _ in range(level_size): node = queue.popleft() # 处理当前层节 ``` 3. **未处理重复入队** - 节入队时未立即标记为已访问,导致同一节多次入队 - ✅ 在节入队时立即标记(而非出队时) --- ### **三、通用问题** 1. **混淆DFS/BFS适用场景** - **DFS适合**:路径存在性、回溯问题、拓扑排序 - **BFS适合**:最短路径、层序遍历、状态空间搜索 - ❌ 误示例:用DFS求无权图最短路径(可能绕远路) 2. **空间复杂度忽视** - **DFS**:递归深度大时易栈溢出(如链状图)→ 改用迭代DFS - **BFS**:队列可能占用大量内存(如完全二叉树)→ 需预估内存 3. **剪枝优化缺失** - 未提前终止无效分支(如已找到更优解时继续搜索) - ✅ 在DFS/BFS中加入条件判断: ```python if current_steps > best_steps: # 剪枝 return ``` --- ### **四、代码示例对比** **DFS(递归)** ```python def dfs(node): if node is target: # 终止条件 return True visited.add(node) for neighbor in node.neighbors: if neighbor not in visited: if dfs(neighbor): # 递归 return True return False ``` **BFS(队列)** ```python from collections import deque def bfs(start): queue = deque([start]) visited = {start} while queue: node = queue.popleft() if node is target: # 找到目标 return True for neighbor in node.neighbors: if neighbor not in visited: visited.add(neighbor) # 入队前标记 queue.append(neighbor) return False ``` --- ### **五、调试技巧** 1. 打印搜索路径或队列状态 2. 在小规模测试用例(如3x3网格)上手动模拟算法流程 3. 使用可视化工具观察搜索过程(如动画演示) 通过理解这些易错并刻意练习,可以显著提升DFS/BFS的实现准确性。建议从经典问题入手(如迷宫问题、二叉树遍历),逐步掌握两种算法的核心逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值