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.."] ]
题解:深度优先搜索,用一个List<Integer> cols保存当前棋盘的情况,cols.get(i)对应第i行(i=0,...n-1)皇后所在的列的索引(0,...,n-1)。几个函数的声明如下所示:
代码如下:
1 public class Solution { 2 private String[] PrintBoard(int n,List<Integer> cols){ 3 String[] answer= new String[n]; 4 for(int i = 0;i < n;i++){ 5 StringBuffer temp = new StringBuffer(); 6 for(int j = 0;j < n;j ++){ 7 temp.append(j == cols.get(i) ? "Q":"."); 8 } 9 answer[i] = temp.toString(); 10 } 11 12 return answer; 13 } 14 private boolean isValid(List<Integer> cols,int col){ 15 for(int i = 0;i < cols.size();i++){ 16 if(cols.get(i) == col) 17 return false; 18 if(cols.size() - i == Math.abs(cols.get(i) - col)) 19 return false; 20 } 21 return true; 22 } 23 private void QueenDfs(int n,int level,List<Integer> cols,List<String[]> result){ 24 if(level == n){ 25 String[] s = PrintBoard(n,cols); 26 result.add(s); 27 return; 28 } 29 30 for(int i = 0;i < n;i++){ 31 if(isValid(cols, i)){ 32 cols.add(i); 33 QueenDfs(n, level+1, cols,result); 34 cols.remove(cols.size()-1); 35 } 36 } 37 } 38 public List<String[]> solveNQueens(int n) { 39 List<String[]> result = new ArrayList<String[]>(); 40 List<Integer> cols = new ArrayList<Integer>(); 41 QueenDfs(n, 0, cols, result); 42 43 return result; 44 } 45 }