题目链接:n-皇后问题
第一种搜索顺序
#include <iostream>using namespace std;const int N = 20;int n;
char g[N][N];
bool row[N], col[N], dg[N], udg[N];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++) cout << g[i] << endl;cout << endl;}return ;}// 尝试不放皇后dfs(x, y + 1, s);// 尝试放置皇后if(!row[x] && !col[y] && !udg[y - x + n] && !dg[x + y]){g[x][y] = 'Q';row[x] = col[y] = udg[y - x + n] = dg[x + y] = true;dfs(x, y + 1, s + 1);row[x] = col[y] = udg[y - x + n] = dg[x + y] = 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;
}
第二种搜索顺序
#include <iostream>using namespace std;const int N = 20;char g[N][N];
int n;
bool col[N], dg[N], udg[N];// 这里的u代表的是一行
void dfs(int u)
{if(u == n){for(int i = 0; i < n; i++) cout << g[i] << endl;cout << endl;return ;}for(int i = 0; i < n; i++)if(!col[i] && !dg[i - u + n] && !udg[u + i]){g[u][i] = 'Q';col[i] = dg[i - u + n] = udg[u + i] = true;dfs(u + 1);g[u][i] = '.';col[i] = dg[i - u + n] = udg[u + i] = 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;
}