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.."] ]
public class Solution {
public List<String[]> solveNQueens(int n) {
List<String[]> boards = new ArrayList<String[]>();
if(n<0) return boards;
char[][] board = new char[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
board[i][j] = '.';
}
}
helper(n, boards, board, 0);
return boards;
}
private void helper(int n, List<String[]> boards, char[][] board, int row) {
if(row==n) {
String[] copy = new String[n];
for(int i=0;i<n;i++) {
copy[i] = new String(board[i]);
}
boards.add(copy);
} else if(row<n) {
for(int i=0;i<n;i++) {
if(check(board, row, i)) {
board[row][i] = 'Q';
helper(n, boards, board, row+1);
board[row][i] = '.';
}
}
}
}
private boolean check(char[][] board, int row, int column) {
for(int i=0;i<row;i++) {
if(board[i][column]=='Q') return false;
if((column- (row-i))>=0 && board[i][column- (row-i)]=='Q') return false;
if((column+(row-i))<board.length && board[i][column+(row-i)]=='Q') return false;
}
return true;
}
}
=========
public class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<List<String>>();
int[] board = new int[n];
helper(board, 0, res);
return res;
}
private void helper(int[] board, int k, List<List<String>> res) {
if (k == board.length) {
List<String> ret = new ArrayList<String>();
for (int i = 0; i < board.length; i++) {
char cs[] = new char[board.length];
Arrays.fill(cs, '.');
cs[board[i]] = 'Q';
ret.add(new String(cs));
}
res.add(ret);
} else if (k < board.length) {
for (int i = 0; i < board.length; i++) {
board[k] = i;
if (check(board, k)) {
helper(board, k + 1, res);
}
}
}
}
private boolean check(int[] board, int k) {
for (int i = 0; i < k; i++) {
if (board[i] == board[k] || Math.abs(board[i] - board[k]) == Math.abs(i - k)) {
return false;
}
}
return true;
}
}
没有评论:
发表评论