DFS & BFS
DFS & BFS
(1)深度优先搜索
题意:求全排列。
#include <bits/stdc++.h>
using namespace std;
const char nl = '\n';
const int N = 25;
int n;
int path[N];
bool st[N];
void dfs(int u){
if (u == n){
for (int i = 0; i < n; ++i) cout << path[i] << ' ';
cout << nl;
return ;
}
for (int i = 1; i <= n; ++i){
if (!st[i]){
path[u] = i;
st[i] = true;
dfs(u + 1);
st[i] = false;
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
dfs(0);
return 0;
}
题意:n-皇后问题。
#include <bits/stdc++.h>
using namespace std;
const char nl = '\n';
const int N = 55;
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) cout << g[i] << nl;
cout << nl;
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(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
g[i][j] = '.';
dfs(0);
return 0;
}
(2)广度优先搜索
题意:迷宫问题,从左上角走到右下角。
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;
const char nl = '\n';
const int N = 110;
int n, m;
int g[N][N], d[N][N];
int dx[4] = {0, -1, 0, 1};
int dy[4] = {-1, 0, 1, 0};
void bfs(){
queue<PII> q;
q.push({0, 0});
d[0][0] = 0;
while (!q.empty()) {
auto t = q.front();
q.pop();
int x = t.first, y = t.second;
for (int i = 0; i < 4; ++i) {
int tx = x + dx[i], ty = y + dy[i];
if (0 <= tx && tx < n && 0 <= ty && ty < m && d[tx][ty] == -1) {
d[tx][ty] = d[x][y] + 1;
q.push({tx, ty});
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m;
for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) d[i][j] = -1;
for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) cin >> g[i][j];
bfs();
cout << d[n - 1][m - 1] << nl;
return 0;
}
/*
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
8
*/