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.."] ]
分析:DFS+backtracking。用三个数组分别用过的列、主对角线、辅对角线。代码如下:
class Solution { public: vector<bool> used_col; vector<bool> used_diag; vector<bool> used_antidiag; vector<vector<string> > solveNQueens(int n) { vector<vector<string> > result; vector<string> path; if(n == 0) return result; this->used_col = vector<bool>(n, false); this->used_diag = vector<bool>(2*n-1, false); this->used_antidiag = vector<bool>(2*n-1, false); dfs(result, path, n, 0); return result; } void dfs(vector<vector<string> > &result, vector<string> &path, int n, int row){ if(row == n){ result.push_back(path); return; } for(int i = 0; i < n; i++){ int diag = row-i+n; int antidiag = row + i; if(!used_col[i] && !used_diag[diag] && !used_antidiag[antidiag]){ used_col[i] = true; used_diag[diag] = true; used_antidiag[antidiag] = true; path.push_back(string(i,'.')+"Q"+string(n-i-1, '.')); dfs(result, path, n, row+1); path.pop_back(); used_col[i] = false; used_diag[diag] = false; used_antidiag[antidiag] = false; } } } };