Get into the habit of writing together! This is the 13th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the event details .
topic
analyze
- Full permutation problem, but this is
**剪枝**
: if you find that the current plan must be illegal, cut the current plan and go back directly
dg: positive diagonal, blue udg: antidiagonal, green
- Question : Why can it be determined that a certain point is above the
g[u][i]
diagonal line ?dg[u + i]
udg[n - u + i]
Answer : Because if k>0, b = y - x, the value of b may be negative, so add n to it
Code 1: You can only put one queen in each line after refining it yourself
#include <iostream>
using namespace std;
const int N = 20;
int n;
char g[N][N]; //将方案记录下来
bool col[N], dg[N], udg[N] ; // 用来判别哪个数已经被用过了,true表示被用过了
void dfs(int u)
{
if (u == n) // 说明已经把所有位置填满了
{
// 直接将方案输出即可
for (int i = 0; i < n; i++) puts(g[i]);
puts("");
return ;
}
// 当u <n的时候,说明没有填完,接下来就枚举一下可以放的位置
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); // 从第0个位置开始看,也就是上图的树根位置
return 0;
}
复制代码
Code 2: Enumeration of one grid and one grid (put/without queen)
#include <iostream>
using namespace std;
const int N = 20;
int n;
char g[N][N]; //将方案记录下来
bool row[N], col[N], dg[N], udg[N] ; // 用来判别哪个数已经被用过了,true表示被用过了
// 从前往后搜,第三个参数记录当前放了多少个皇后
void dfs(int x, int y, int s)
{
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])
{
g[x][y] = 'Q';
row[x] = col[y] = dg[x + y] = udg[x - y + n] = true;
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;
}
复制代码