算法基础模板——DFS与BFS算法
1. DFS与BFS算法的比较
这两种算法一般都是解决树与图的遍历,主要的区别如下
算法 | 数据结构 | 空间复杂度 | 有无固定模板 | 解决哪一类问题 |
---|---|---|---|---|
DFS | stack | O(h) | 无 | 枚举所有的可能,一般有回溯与剪枝 |
BFS | queue | O(2^h) | 有 | 有最短概念,最少的次数 |
2.DFS
DFS内有固定的模板,主要是思路,比较常见的问题有全排列问题
- 全排列问题
#include <iostream>
using namespace std;
const int N = 10;
int n;
int path[N],state[N];
void dfs(int u)
{
if (u == n)
{
for (int i = 0; i < n; i ++ ) printf("%d ", path[i]);
puts("");
return;
}
for (int i = 1; i <= n; i ++ )
if (!state[i])
{
path[u] = i ;
state[i] = true;
dfs(u + 1);
state[i] = false;
}
}
int main()
{
scanf("%d", &n);
dfs(0, 0);
return 0;
}
-
N皇后问题
第一种搜索顺序
#include <iostream>
using namespace std;
const int N = 10;
int n;
bool row[N], col[N], dg[N * 2], udg[N * 2];
char g[N][N];
void dfs(int x, int y, int s)
{
if (s > n) return;
if (y == n) y = 0, x ++ ;
if (x == n)
{
if (s == n)
{
for (int i = 0; i < n; i ++ ) puts(g[i]);
puts("");
}
return;
}
g[x][y] = '.';
dfs(x, y + 1, s);
if (!row[x] && !col[y] && !dg[x + y] && !udg[x - y + n])
{
row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
g[x][y] = 'Q';
dfs(x, y + 1, s + 1);
g[x][y] = '.';
row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
}
}
int main()
{
cin >> n;
dfs(0, 0, 0);
return 0;
}
第二种搜索顺序
#include <iostream>
using namespace std;
const int N = 20;
int n;
char g[N][N];
bool col[N], dg[N], udg[N];
void dfs(int u)
{
if (u == n)
{
for (int i = 0; i < n; i ++ ) puts(g[i]);
puts("");
return;
}
for (int i = 0; i < n; i ++ )
if (!col[i] && !dg[u + i] && !udg[n - u + i])
{
g[u][i] = 'Q';
col[i] = dg[u + i] = udg[n - u + i] = true;
dfs(u + 1);
col[i] = dg[u + i] = udg[n - u + i] = false;
g[u][i] = '.';
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ )
for (int j = 0; j < n; j ++ )
g[i][j] = '.';
dfs(0);
return 0;
}
3. BFS
注意只有最权重为1的最短路问题才能够使用宽搜
1、 模板
queue <-初始状态
while(queue不为空){
将队头拿出来
扩展队列
}
2、 例子
-
走迷宫
#include <cstring> #include <iostream> #include <algorithm> #include <queue> using namespace std; typedef pair<int, int> PII; const int N = 110; int n, m; int g[N][N], d[N][N]; int bfs() { queue<PII> q; memset(d, -1, sizeof d); d[0][0] = 0; q.push({0, 0}); int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; while (q.size()) { auto t = q.front(); q.pop(); for (int i = 0; i < 4; i ++ ) { int x = t.first + dx[i], y = t.second + dy[i]; if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) { d[x][y] = d[t.first][t.second] + 1; q.push({x, y}); } } } return d[n - 1][m - 1]; } int main() { cin >> n >> m; for (int i = 0; i < n; i ++ ) for (int j = 0; j < m; j ++ ) cin >> g[i][j]; cout << bfs() << endl; return 0; }
参考:
作者:yxc
链接:https://www.acwing.com/activity/content/code/content/47097/