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.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> solutions; vector<int> queens(n,-1); unordered_set<int> columns;//列 unordered_set<int> diagonals1;//对角线1 unordered_set<int> diagonals2;//对角线2 backtrack(solutions,queens,n,0,columns,diagonals1,diagonals2); return solutions; } void backtrack(vector<vector<string>> &solutions,vector<int> &queens,int n,int row,unordered_set<int> &columns,unordered_set<int> diagonals1,unordered_set<int> diagonals2) { if(row == n){ vector<string> board = generateBoard(queens,n); solutions.push_back(board); } else{ for(int i=0;i<n;++i){ if(columns.find(i)!= columns.end()){ continue; } int diagonal1 = row -i; if(diagonals1.find(diagonal1) != diagonals1.end()){ continue; } int diagonal2 = row +i; if(diagonals2.find(diagonal2) != diagonals2.end()){ continue; } queens[row] = i; columns.insert(i); diagonals1.insert(diagonal1); diagonals2.insert(diagonal2); backtrack(solutions,queens,n,row+1,columns,diagonals1,diagonals2); queens[row] = -1; columns.erase(i); diagonals1.erase(diagonal1); diagonals2.erase(diagonal2); } } } vector<string> generateBoard(vector<int> &queens,int n){ vector<string> board; for(int i=0;i<n;++i) { string row = string(n,'.'); row[queens[i]] = 'Q'; board.push_back(row); } return board; } };
注意:回溯算法,深度优先查找。