leetcode-51. 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..”]
]
就是典型的n皇后问题,如此经典的题目能不能做出来跟聪明无关,唯手熟尔。
总的来说分三部分
- 一部分用来判断终止条件,即需要判断第len行,并且将boolean转换成
List<String>
因为java在做String操作的时候实际上是很慢的,这个是java使用习惯的问题了。这个答案超过了72%的答案运算结果。显然是因为使用了boolean[][]而非String - 第二部分是迭代条件,for循环内表示当前考虑的行数,len表示列数
- 第三部分就是判断当前i行和len列是否可以填充true。
public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> ret = new ArrayList<List<String>>();
boolean [][] mat = new boolean[n][n];
helper(ret,mat,0);
return ret;
}
private void helper(List<List<String>> ret, boolean[][] mat,int len){
if(len==mat.length){
ArrayList<String> tmp = new ArrayList<String>();
for(boolean[] list : mat){
StringBuilder sb = new StringBuilder();
for(boolean f : list)
if(f)
sb.append("Q");
else
sb.append(".");
tmp.add(sb.toString());
}
ret.add(tmp);
return ;
}
for(int i=0;i<mat.length;i++){
if(verify(mat,len,i)){
mat[len][i] = true;
helper(ret,mat,len+1);
mat[len][i] = false;
}
}
}
private boolean verify(boolean[][] mat, int ni , int nj){
for(int i = 0 ; i<ni ; i++){
if(mat[i][nj]) return false;
if(ni-i-1>=0 && nj-i-1>=0 && mat[ni-i-1][nj-i-1]) return false;
if(ni-i-1>=0 && nj+i+1<mat.length && mat[ni-i-1][nj+i+1]) return false;
}
return true;
}
}