题目:
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.
解法同LeetCode 刷题记录52. N-Queens II中的解法1一直,只要我们在对应皇后的位置直接变为‘Q’
c++:
c++直接可以初始化一个n*n为’.‘的列表,然后遍历这个列表在对应位置变为’Q’
注意我们下标是从1开始的,注意对应的要减一
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<int> pos(n+1,0);
dfs(pos , 1 ,n ,res);
return res;
}
void dfs(vector<int>& pos, int row, int n,vector<vector<string>>& res){
if(row == n + 1){
vector<string> path(n, string(n,'.'));
for(int i = 1; i <= n; i++){
path[i-1][pos[i] - 1] = 'Q';
}
res.push_back(path);
return;
}
for(int col = 1; col <= n; col++){
if(!isVaild(pos,row,col)) continue;
pos[row] = col;
dfs(pos,row + 1,n,res);
pos[row] = 0;
}
}
bool isVaild(vector<int>& pos, int row, int col){
for(int i = 1; i < row; i++){
if(col == pos[i] || abs(row - i) == abs(col - pos[i])){
return false;
}
}
return true;
}
};
java:
java不能直接生成n*n为’.'的列表,所以我们依次生成每行
class Solution {
public List<List<String>> solveNQueens(int n) {
int[] pos = new int[n+1];
List<List<String>> res = new ArrayList<>();
dfs(pos , 1 ,n,res);
return res;
}
private void dfs(int[] pos, int row, int n, List<List<String>> res){
if(row == n + 1){
List<String> path= new ArrayList<>();
for(int i = 1; i <= n; i++){
char[] t = new char[n];
Arrays.fill(t,'.');
t[pos[i] - 1] = 'Q';
path.add(new String(t));
}
res.add(path);
return;
}
for(int col = 1; col <= n; col++){
if(!isVaild(pos,row,col)) continue;
pos[row] = col;
dfs(pos,row + 1,n,res);
pos[row] = 0;
}
}
private boolean isVaild(int[] pos, int row, int col){
for(int i = 1; i < row; i++){
if(col == pos[i] || Math.abs(row - i) == Math.abs(col - pos[i])){
return false;
}
}
return true;
}
}
python:
用[’.’ * q + ‘Q’ + ‘.’ * (n - q - 1) for q in pos]语句生成每一种情况,遍历每一行的位置q,每一行应该有q 个’.‘加’Q’再加q 个’.’ (n - q - 1)
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
res = []
pos = [-1] * n
self.dfs(pos , 0 ,n,res)
return res
def dfs(self, pos, row, n,res):
if row == n:
res.append(['.' * q + 'Q' + '.' * (n - q - 1) for q in pos]);
return
for col in xrange(n):
if not self.isVaild(pos,row,col): continue
pos[row] = col
self.dfs(pos,row + 1,n,res)
pos[row] = -1
def isVaild(self,pos, row, col):
for i in xrange(row):
if col == pos[i] or abs(row - i) == abs(col - pos[i]):
return False
return True