为什么不用dfs
太慢了 dfs 必须搜索所有方案,再从中选择合适的方案
什么是bfs
广度优先搜索,搜索逻辑是:
1.访问起点走1步可以到达的所有点
2.访问起点走2步可以到达的所有点
3.访问起点走3步可以到达的所有点
一般用于求最少步数
当第一次访问到这个点时,此时的步数就一定是起点到它的最小步数
如何实现
先访问先加入序列的元素,用队列辅助实现
流程:
1.起点入队
2.只要队列为不空,就循环
3.每次循环,取出队首,看队首再走一步可以到哪些点,把它们加入到队列末尾。
细节:
每个点只走一次,所以时间复杂度是
dfs和bfs
找所有路线,dfs
找最优路线,bfs
cpp
#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;
}