您的位置:首页 > 产品设计 > UI/UE

[Leetcode] N-Queens (Java)

2014-01-08 17:00 417 查看
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.."]
]


N皇后问题,DFS

public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
ArrayList<String[]> res = new ArrayList<String[]>();
char[][] chars = new char

;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
chars[i][j]='.';
}
}
dfs(chars, res, 0, n);
return res;
}
private void dfs(char[][] chars,ArrayList<String[]> res,int index,int n){
if(index==n){
String[] strs = new String
;
for(int i=0;i<chars.length;i++) {
strs[i]=new String(chars[i]);
}
res.add(strs);
return;
}
for(int i=0;i<chars[index].length;i++){
if(check(chars,index,i)){
chars[index][i]='Q';
dfs(chars, res, index+1, n);
chars[index][i]='.';
}
}
}
private boolean check(char[][] chars, int index, int pivot) {
for(int i=0;i<index;i++){
if(chars[i][pivot]=='Q')
return false;
}
for(int i=index-1, j=pivot-1;i>=0&&j>=0;i--,j--){
if(chars[i][j]=='Q')
return false;
}
for(int i=index-1, j=pivot+1;i>=0&&j<chars[i].length;i--,j++){
if(chars[i][j]=='Q')
return false;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: