Leetcode, NQueens2
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int _count;
vector<int> columns; //已占据了哪些列
vector<int> main_diag; //已占据主对角线
vector<int> anti_diag; //已占据副对角线
void dfs(vector<int> &C, int row)
{
const int N = C.size();
if (row == N)
{
++_count;
return;
}
//扩展状态,一列一列的试
for (int j = 0; j < N; ++j)
{
//main_diag, anti_diag是 2 * n个0的序列,main_diag占据[n, 2n - 1],anti_diag占据[0, n - 1]
//主对角线上: i - j = 固定值,副对角线上:i + j = 固定值
const bool ok = columns[j] == 0 && main_diag[row + j] == 0 && anti_diag[row - j + N] == 0;
if (!ok) continue;
//执行扩展动作
C[row] = j;
columns[j] = main_diag[row + j] = anti_diag[row - j + N] = 1;
dfs(C, row + 1);
//撤销动作
//C[row] = 0
columns[j] = main_diag[row + j] = anti_diag[row - j + N] = 0;
}
}
//时间复杂度O(n!),空间复杂度O(n)
int solution(int n)
{
_count = 0;
columns = vector<int>(n, 0);
main_diag = vector<int>(2 * n, 0);
anti_diag = vector<int>(2 * n, 0);
vector<int> C(n, 0); //C[i]表示第i行皇后所在列编号
dfs(C, 0);
return _count;
}
int main()
{
auto res = solution(4);
cout << res << endl; //2;
return 0;
}