leetcode 72: N-Queens
N-QueensMar
20 '12
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.."] ]
need improvement!
public class Solution {
public ArrayList<String[]> solveNQueens(int n) {
// Start typing your Java solution below
// DO NOT write main() function
char[][] res = new char[n][n];
for(int i=0; i<n; i++) {
for(int j=0;j<n;j++) {
res[i][j] = '.';
}
}
boolean[][] board = new boolean[n][n];
ArrayList<String[]> resList = new ArrayList<String[]>();
qRec(resList,res,board, 0);
//convert char[][] to ArrayList<String[]>;
return resList;
}
private void qRec(ArrayList<String[]> resList, char[][] res, boolean[][] board ,int level){
int n = res.length;
if( level >= n) {
String[] ss = new String[n];
for(int i=0;i<n;i++) {
ss[i] = new String(res[i]);
}
resList.add(ss);
return;
}
for(int i=0; i<n; i++) {
res[level][i] = 'Q';
board[level][i] = true;
if( check( res,board, i, level) ) {
qRec(resList, res, board, level+1);
}
board[level][i] = false;
res[level][i] = '.';
}
}
private boolean check( char[][] res, boolean[][] board, int col ,int line){
int n = res.length;
for(int j=0; j<line; j++) {
if( board[j][col] == true )
return false;
for(int k=0; k<n; k++) {
if( board[j][k]==true && line-j==Math.abs(col-k))
return false;
}
}
return true;
}
}
浙公网安备 33010602011771号