作者:disappearedgod
时间:2014-9-10
题目
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.."] ]
想法
1. 先判断是否是可以放置的点。
2. 添加能够放置的位置。
3. 如果都放置完返回结果。
4.添加到列表中。
解法
代码
public class Solution {
public List<String[]> solveNQueens(int n) {
ArrayList<String[]> retlist = new ArrayList<String[]>();
if(n ==0)
return retlist;
StringBuffer sb = new StringBuffer();
for(int i = 0; i < n; i++)
sb.append('.');
int[] column = new int[n];
solveNQueens(0, column, retlist, sb.toString());
return retlist;
}
public void solveNQueens(int row, int[] columns, ArrayList<String[]> results, String s){
if(row == columns.length){
String[] retArr = new String[ columns.length];
for(int i = 0 ; i < columns.length; i++){
StringBuffer sb = new StringBuffer(s);
int pos = columns[i];
sb.replace(pos,pos+1,"Q");
retArr[i] = sb.toString();
}
results.add(retArr);
}
else{
for(int col = 0; col < columns.length; col++){
if(
checkValid(columns, row, col)
){
columns[row] = col;
solveNQueens(row+1, columns, results, s);
}
}
}
}
boolean checkValid(int[] columns, int row, int column){
for(int r = 0; r < row; r++){
//1. columns[r]!= column
//2. r != row
//3. row - r != abs(column - columns[r])
int c = columns[r];
if(c == column || r == row || Math.abs(c - column) == row - r)
return false;
}
return true;
}
}
结果
Submit Time | Status | Run Time | Language |
---|---|---|---|
2 minutes ago | Accepted | 424 ms | java |