题目链接:
https://leetcode.com/problems/n-queens-ii/
题目描述:
输入N,输出N皇后满足的可能结果,即N个皇后不在同一行,同一列,同一对角线。
题目分析:
直接回溯法即可,只需确定Qi占了哪一行 ,那一列,哪条对角线(正负对角线)。
标记是否被占用:Qi在ri行,ci列时
行: 按行ri + 1递归进去,故行号不可能重复
列: col[ci] = 1;
正对角线: x1[ri + ci] = 1;
反对角线: x2[ri + n – 1 – ci] = 1;
AC代码:
#include<stdio.h>
#include<string>
using namespace std;
int col[101];
int x1[202];
int x2[202];
int ans = 0;
class Solution {
public:
int totalNQueens(int n) {
ans = 0;
memset(col, 0, sizeof(col));
memset(x1, 0, sizeof(x1));
memset(x2, 0, sizeof(x2));
solve(0, n);
// printf("%d\n", ans);
return ans;
}
void solve(int ri, int n) {
if (ri == n) {
ans++;
return;
}
int ci;
for (ci = 0; ci < n; ci++) {
if (col[ci] || x1[ri + ci] || x2[ri + n - 1 - ci]) continue;
col[ci] = 1;
x1[ri + ci] = 1;
x2[ri + n - 1 - ci] = 1;
solve(ri + 1, n);
col[ci] = 0;
x1[ri + ci] = 0;
x2[ri + n - 1 - ci] = 0;
}
}
};
int main() {
Solution s;
s.totalNQueens(13);
return 0;
}