N-Queens @LeetCode

2014-11-24 08:41:54 · 作者: · 浏览: 1
经典的8皇后,递归回溯可解。同时还学了StringBuilder里面一个setCharAt()很方便的方法。
package Level4;  
  
import java.util.ArrayList;  
import java.util.Arrays;  
  
/** 
 *  
 * N-Queens 
 *  
 * The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. 

https://www.cppentry.com/upload_files/article/76/1_dfuzf__.png 

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 S51 {  
  
    public static void main(String[] args) {  
        System.out.println(solveNQueens(4));  
    }  
  
    public static ArrayList solveNQueens(int n) {  
        ArrayList ret = new ArrayList();  
        int[] queenList = new int[n];  
        placeQueen(queenList, 0, n, ret);  
        return ret;  
    }  
      
    // 递归回溯8皇后,关键记录下到达了哪一行了  
    public static void placeQueen(int[] queenList, int row, int n, ArrayList ret){  
        // Base Case, 已经完成任务了  
        if(row == n){  
            StringBuilder[] sol = new StringBuilder[n];  
              
            // 对数组内每一个对象都要new出其对象  
            for(int i=0; i