题解 | #N皇后问题#
N皇后问题
http://www.nowcoder.com/practice/c76408782512486d91eea181107293b6
class Solution {
public:
/**
*
* @param n int整型 the n
* @return int整型
*/
void function(int n, int num, int& res, vector<bool>& pathRow, vector<bool>& pathCol, vector<bool>& pathX, vector<bool>& pathY) {
if(num == n) {
res++;
return;
}
// num 代表行数,i代表列数,n-num+i和num+i代表两个斜向
for(int i = 0; i < n; i++) {
if(!pathRow[num] && !pathCol[i] && !pathX[n-num+i] && !pathY[num + i]) {
pathRow[num] = true;
pathCol[i] = true;
pathX[n-num+i]=true;
pathY[num + i] = true;
function(n, num + 1, res, pathRow, pathCol, pathX, pathY);
pathRow[num] = false;
pathCol[i] = false;
pathX[n-num+i] = false;
pathY[num + i] = false;
}
}
}
int Nqueen(int n) {
// write code here
vector<bool> pathRow(10);
vector<bool> pathCol(10);
vector<bool> pathX(20);
vector<bool> pathY(20);
int res = 0;
function(n, 0, res, pathRow, pathCol, pathX, pathY);
return res;
}
};