跳到正文

个人记录

3.8 bfd-1

yxyxyx_约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年5月18日
更新
2026年5月18日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1

为什么不用dfs

太慢了 dfs 必须搜索所有方案,再从中选择合适的方案

什么是bfs

广度优先搜索,搜索逻辑是:

1.访问起点走1步可以到达的所有点

2.访问起点走2步可以到达的所有点

3.访问起点走3步可以到达的所有点

一般用于求最少步数

当第一次访问到这个点时,此时的步数就一定是起点到它的最小步数

如何实现

先访问先加入序列的元素,用队列辅助实现

流程:

1.起点入队

2.只要队列为不空,就循环

3.每次循环,取出队首,看队首再走一步可以到哪些点,把它们加入到队列末尾。

细节:

每个点只走一次,所以时间复杂度是 O(n∗m)O(n*m)

dfs和bfs

找所有路线,dfs

找最优路线,bfs

cpp

C++
#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int N = 405;

struct P
{
	int x, y, st;
};

int n, m;
int d[4][2] = {0, 1, 1, 0, -1, 0, 0, -1};
int vis[N][N];
char mp[N][N];

void bfs()
{
	memset(vis, 0, sizeof vis);
	queue<P> q;

	q.push({1, 1, 1});
	vis[1][1] = 1;

	while (q.size())
    {
		P now = q.front();
		q.pop();

		if (now.x == n && now.y == m)
        {
			cout << now.st;
			return ;
		}
		for (int i=0; i<4; i++)
        {
			int nx = now.x + d[i][0];
			int ny = now.y + d[i][1];

			if (nx < 1 or nx > n or ny < 1 or ny > m) continue;
			if (mp[nx][ny] == '#' or vis[nx][ny]) continue;

			q.push({nx, ny, now.st+1});
			vis[nx][ny] = 1;
		}
	}
}

int main()
{
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin >> n >> m;
	for (int i=1; i<=n; i++)
    {
		for (int j=1; j<=m; j++)
        {
			cin >> mp[i][j];
		}
	}
    bfs();
	return 0;
}
原文