Description
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.
分析
题目的意思是:有n个皇后在一个棋盘上,然后皇后上下左右对角线不能共线。输出所有的放置方案。
- 这是一个典型的递归求解的问题,下面是一个经典的做法。由于棋盘的每一排只能放一个,所以用x的下标代表棋盘的行,x的值代表列,所以用一个一维的数组递归求解就行了,节省了空间,然后递归遍历的每个位置都需要检查一下是否跟以前的皇后的位置有冲突,找一个没有冲突的位置作为当前行的皇后的位置,主要思想就是这样的。
C++实现
class Solution {
int x[19];
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> out;
string s1(n,'.');
for(int i=0;i<n;i++){
out.push_back(s1);
}
solve(res,out,0,n);
return res;
}
void solve(vector<vector<string>>& res,vector<string> out,int start,int n){
if(start==n){
res.push_back(out);
return ;
}
for(int i=0;i<n;i++){
x[start]=i;
out[start][i]='Q';
if(check(start)){
solve(res,out,start+1,n);
}
out[start][i]='.';
}
}
bool check(int m){
for(int i=0;i<m;i++){
if(abs(x[m]-x[i])==abs(m-i)||x[m]==x[i]) return false;
}
return true;
}
};
Python实现
实现跟上面的思路一样。
class Solution:
def __init__(self):
# 下标代表行,x的值代表列
self.x = [0]*19
def solve(self, out, start, n, res):
if start==n:
res.append([''.join(item) for item in out])
return
for i in range(n):
self.x[start]=i
out[start][i]='Q'
if self.check(start):
self.solve(out,start+1, n, res)
out[start][i]='.'
def check(self, m):
for i in range(m):
if abs(self.x[m]-self.x[i])==abs(m-i) or self.x[m]==self.x[i]:
return False
return True
def solveNQueens(self, n: int) -> List[List[str]]:
res = []
s = ['.']*n
out = []
for i in range(n):
out.append(s[:])
self.solve(out, 0,n, res)
return res