题目:
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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
思路:回溯法经典题目。
class Solution {
public:
bool is_valid(const vector<vector<int>>& board, int n, int row, int col) {
for (int i = 0; i < row; ++i) {
if (board[i][col] == 1) return false;
if (col - (row - i) >= 0 && board[i][col-(row-i)] == 1) return false;
if (col + (row - i) < n && board[i][col+(row-i)] == 1) return false;
}
return true;
}
void nqueens_helper(vector<vector<int>>& board, int row, int n,
vector<vector<string>>& result) {
if (row == n) { //a valid board, save it
vector<string> new_board;
for (int i = 0; i < n; ++i) {
string new_row;
for (int j = 0; j < (int)board[0].size(); ++j) {
new_row += board[i][j] == 0 ? '.' : 'Q';
}
new_board.push_back(new_row);
}
result.push_back(new_board);
return;
}
for (int j = 0; j < n; ++j) { //try every column for the current row
if (is_valid(board, n, row, j)) {
board[row][j] = 1;
nqueens_helper(board, row + 1, n, result); //next row
board[row][j] = 0; //backtracking
}
}
}
vector<vector<string> > solveNQueens(int n) {
vector<vector<int>> board(n, vector<int>(n, 0));
vector<vector<string>> result;
nqueens_helper(board, 0, n, result);
return result;
}
};
总结:复杂度为O(n!).