基本特性
1. 数据结构:stack
2. 空间复杂度:O(h)
3. 不具备最短性
4. 两个重要操作:回溯(注意恢复现场) + 剪枝
排列数字
原理图
#include <iostream>
using namespace std;
const int N = 10;
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] << ' ';
puts("");
return;
}
for (int i = 1; i <= n; i ++)
{
if (!st[i])
{
path[u] = i;
st[i] = true;
dfs(u + 1); // 进入下一位
// 回溯,要恢复现场
path[u] = 0;
st[i] = false;
}
}
}
int main()
{
cin >> n;
dfs(0); // 从第0位开始
return 0;
}
n-皇后问题
第一种做法:全排列
和排列数字思想相似,注意剪枝
每一行只会有一个皇后,所以可以按行枚举,看每一行的皇后应该放到哪个位置上
#include <iostream>
using namespace std;
const int N = 10;
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 ++)
{
// u:行号(y) i:列号(x)
// y = x + b; --> b = y - x; // 防止出现负数,+ n
// y = -x + b; --> b = y + x;
if (!col[i] && !dg[u + i] && !udg[u - i + n])
{
g[u][i] = 'Q';
col[i] = dg[u + i] = udg[u - i + n] = true;
dfs(u + 1);
g[u][i] = '.';
col[i] = dg[u + i] = udg[u - i + n] = false;
}
}
}
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;
}
第二种做法:一个位置一个位置判断
#include <iostream>
using namespace std;
const int N = 10;
int n;
char g[N][N];
bool row[N], col[N], dg[N * 2], udg[N * 2];
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;
}
// 该点不放皇后
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);
row[x] = col[y] = dg[x + y] = udg[x - y + n] = false;
g[x][y] = '.';
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++)
for (int j = 0; j < n; j ++)
g[i][j] = '.';
dfs(0, 0, 0);
return 0;
}