【題目--33. N-Queens】
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
n皇后問題是將n個皇后放置在n*n的棋盤上,皇后彼此之間不能相互攻擊。
給定一個整數n,返回所有不同的n皇后問題的解決方案。
每個解決方案包含一個明確的n皇后放置佈局,其中“Q”和“.”分別表示一個女王和一個空位置。
【樣例】
對於4皇后問題存在兩種解決的方案:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
【解題思路】
深度遍歷+回溯。
1. 從上到下,從左到右,判斷某個位置是否可以放皇后,可以放,轉2,不可以,轉3;
2. 放置皇后,並判斷是否已經放置N個皇后,如果是,記錄結果並回溯;否則轉1,遞歸判斷下一行能否放置皇后;
3. 判斷本行下一列是否可以放置皇后。如果本列無法放置皇后,剪枝;否則查看下一列能否放置皇后。即,可以放置,就往下找;放不了,就往回看,拜託上層變一變,看能不能繼續往下找,直到第一層都試過最後一列的位置,程序結束。
由於需要記錄所有可行結果並輸出,在每次得到可行結果時,將當前結果保存,並將Q還原爲".",方便回溯。
【AC代碼】
class Solution {
public:
/**
* Get all distinct N-Queen solutions
* @param n: The number of queens
* @return: All distinct solutions
* For example, A string '...Q' shows a queen on forth position
*/
//判斷位置(row, col)是否可以放置皇后
bool judgeQ(vector<string> &queen, int row, int col) {
int n = queen.size();
for (int i = 0; i < row; ++i) {
for (int j = 0; j < n; ++j) {
if (queen[i][j] == 'Q') {
if (i == row || j == col || abs(row-i) == abs(col-j))
return false;
}
}
}
return true;
}
//遞歸放置皇后
void placeQ(vector<string> &queen, vector<vector<string> > &res, int row, int col) {
int n = queen.size();
//超過棋盤大小,結束
if (row == n || col == n)
return;
//(row, col)處可以放置皇后
if (judgeQ(queen, row, col)){
queen[row][col] = 'Q';
//如果皇后放在最後一行,得到一個可行解,否則爲中間狀態
if (row == n-1) {
//將可行解入棧,將置爲Q的位置恢復爲.,回溯
res.push_back(queen);
queen[row][col] = '.';
return;
} else {
//中間狀態,繼續判斷下一行是否可以放置皇后,如果下一行不可以放置,將該點還原,判斷改行的下一列是否可以放置皇后
placeQ(queen, res, row+1, 0);
queen[row][col] = '.';
placeQ(queen, res, row, col+1);
}
} else {
//當前位置無法放置皇后,如果已經是該行的最後一列,表示當前行無法放置,返回;否則,嘗試當前行的下一列
if (col == n-1)
return;
else
placeQ(queen, res, row, col+1);
}
}
vector<vector<string> > solveNQueens(int n) {
// write your code here
vector<vector<string> > res;
if (n < 0)
return res;
int row = 0, col = 0;
string str(n, '.');
vector<string> queen(n, str);
placeQ(queen, res, row, col);
return res;
}
};
加上中間輸出後,可以更加直觀瞭解整個過程。
對於4皇后問題。
先將皇后放在(0, 0),
尋找row = 1時可以放置皇后的位置,得到(1, 2),
當前情況下, row = 2時無法放置皇后,(1, 2)還原,找到(1, 3)可以放置皇后,
繼續判斷當前情況下row = 2能否放置皇后,找到(2, 1),
嘗試row = 3, 無法放置,(2, 1)還原,row=2無法放置,row=1已經放置在最後一列,沒有可選位置,(0, 0)還原,嘗試(0,1)。
【題目--34. N-Queens II】
根據n皇后問題,現在返回n皇后不同的解決方案的數量而不是具體的放置佈局。
只需要改變得到可行解時對結果的處理。不用將現有的結果保存,只需要用一個整數記錄可行解的個數即可。
【AC代碼】
class Solution {
public:
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
int totalNQueens(int n) {
// write your code here
int res = 0;
if (n < 0)
return res;
int row = 0, col = 0;
string str(n, '.');
vector<string> queen(n, str);
placeQ(queen, n, res, row, col);
return res;
}
void placeQ(vector<string> &queen, int n, int &res, int row, int col) {
if (row >= n || col >= n)
return;
//當前位置可以放置皇后
if (judgeQ(queen, n, row, col)) {
queen[row][col] = 'Q';
//最後一行放置皇后,得到可行結果
if (row == n-1) {
++res;
queen[row][col] = '.';
return;
} else {
//中間行放置皇后,遞歸
placeQ(queen, n, res, row+1, 0);
queen[row][col] = '.';
placeQ(queen, n, res, row, col+1);
}
} else {
//當前位置不可以放置皇后
//當前行已經嘗試至最後一列,回溯
if (col == n-1)
return;
else
placeQ(queen, n, res, row, col+1);
}
}
bool judgeQ(vector<string> &queen, int n, int row, int col) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (queen[i][j] == 'Q') {
if (i == row || j == col || abs(row-i) == abs(col-j))
return false;
}
}
}
return true;
}
};
因爲只需要輸出結果的數量,只對結果計數,不保存中間結果,可以使用一維數組queen記錄皇后放置的位置,queen[i]表示第i行皇后所在的位置,遍歷所有的可能,如果有可行解,記錄結果的數量+1。具體代碼如下:
class Solution {
public:
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
int totalNQueens(int n) {
// write your code here
int res = 0;
if (n < 0)
return res;
int row = 0, col = 0;
//queen記錄第k行皇后所放位置
vector<int> queen(n);
placeQ(queen, res, n, 0);
return res;
}
void placeQ(vector<int> &queen, int &res, int n, int k) {
if (k == n) {
++res;
return;
}
//嘗試所有可以放皇后的位置
for (int i = 0; i < n; ++i) {
if (!judgeQ(queen, k, i))
continue;
queen[k] = i;
placeQ(queen, res, n, k+1);
}
}
bool judgeQ(vector<int> &queen, int row, int col) {
for (int i = 0; i < row; ++i) {
//同一列
if (queen[i] == col)
return false;
//同一條斜線
if (abs(i-row) == abs(queen[i]-col))
return false;
}
return true;
}
};