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.."]
]
Solution
public class Solution { public List<String[]> solveNQueens(int n) { boolean[][] board = new boolean[n][n]; List<String[]> solution = new ArrayList<String[]>(); solveNQueens(board, 0, solution); return solution; } public void solveNQueens(boolean[][]board, int row, List<String[]> solution) { if(row==board.length) { String[] oneSolution = new String[board.length]; for(int i=0; i<board.length;i++) { StringBuilder sb = new StringBuilder(); for(int j=0; j<board[0].length; j++) if(board[i][j]) sb.append('Q'); else sb.append('.'); oneSolution[i] = sb.toString(); } solution.add(oneSolution); return; } for(int i=0; i<board[0].length; i++) { if(canAdd(board, row, i)) { board[row][i]=true; solveNQueens(board, row+1, solution); board[row][i]=false; } } } private boolean canAdd(boolean[][] board, int row, int col) { for(int i=0; i<row; i++) { if(board[i][col]) return false; if(col+i-row>=0 && board[i][col+i-row]) return false; if(col+row-i<board[0].length && board[i][col+row-i]) return false; } return true; } }
No comments :
Post a Comment