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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
回溯算法,参考这个,比较好理解一点。
假设数组为int state[n], state[i]表示第 i 行皇后所在的列。那么在新的一行 k 放置一个皇后后:
- 判断列是否冲突,只需要看state数组中state[0…k-1] 是否有和state[k]相等;
- 判断对角线是否冲突:如果两个皇后在同一对角线,那么|row1-row2| = |column1 - column2|,(row1,column1),(row2,column2)分别为冲突的两个皇后的位置
1 class Solution { 2 private: 3 vector<vector<string> > res; 4 public: 5 vector<vector<string> > solveNQueens(int n) { 6 vector<int> state(n, -1); 7 helper(state, 0); 8 return res; 9 } 10 void helper(vector<int> &state, int row) 11 {//放置第row行的皇后 12 int n = state.size(); 13 if(row == n) 14 { 15 vector<string>tmpres(n, string(n,'.')); 16 for(int i = 0; i < n; i++) 17 tmpres[i][state[i]] = 'Q'; 18 res.push_back(tmpres); 19 return; 20 } 21 for(int col = 0; col < n; col++) 22 if(isValid(state, row, col)) 23 { 24 state[row] = col; 25 helper(state, row+1); 26 state[row] = -1; 27 } 28 } 29 30 bool isValid(vector<int> &state, int row, int col) 31 { 32 for(int i = 0; i < row; i++) 33 if(state[i] == col || abs(row - i) == abs(col - state[i])) 34 return false; 35 return true; 36 } 37 };