
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.."] ]
[Thoughts]: Queens数组,index为行号,value是改行放queen的列号
public class Solution {
public List<String[]> solveNQueens(int n) {
List<String[]> res = new ArrayList<String[]>();
int[] q = new int[n];
placeQ(res, q, 0);
return res;
}
public void placeQ(List<String[]> res, int[] q, int row){
if(row==q.length){
addResult(res, q);
return;
}
for(int i=0; i<q.length; i++){
if(isValid(q, row, i)){
q[row] = i;
placeQ(res, q, row+1);
}
}
}
public boolean isValid(int[] q, int row, int col){
for(int i=0; i<row; i++){
if(q[i] == col)
return false;
if(Math.abs(i-row) == Math.abs(q[i]-col))
return false;
}
return true;
}
public void addResult(List<String[]> res, int[] q){
String[] line = new String[q.length];
for(int i=0; i<q.length; i++){
StringBuilder sb = new StringBuilder();
for(int j=0; j<q.length; j++){
sb.append(q[i]==j ? "Q" : ".");
}
line[i] = sb.toString();
}
res.add(line);
}
}
II: Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
和I的思路一样,区别就是不用去拼写string,设置一个全局变量count去数个数就行了。
public class Solution {
private int count;
public int totalNQueens(int n) {
if(n<=0) return -1;
int[] queens = new int[n];
placeQueens(queens, 0);
return count;
}
public void placeQueens(int[] queens, int row){
//only difference with I, 就是处理solution的方式,此题计数就可以了。
if(row==queens.length){
count++;
return;
}
for(int i=0; i<queens.length; i++){
if(isValid(queens, row, i)){
queens[row] = i;
placeQueens(queens, row+1);
}
}
}
public boolean isValid(int[] queens, int row, int col){
for(int i=0; i<row; i++){
if(queens[i]==col)
return false;
if(Math.abs(row-i) == Math.abs(col-queens[i]))
return false;
}
return true;
}
}
No comments:
Post a Comment