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.

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.."]
]

比N-Queens II稍微麻煩一點,其實本質是一樣的,解法參考N-Queens II 那道題,區別就是在if(row == n)的時候將list加入,注意:如果有標誌可以標記的時候,最好在遞歸最內層加入list,否則容易出錯。

注意輸出:此題的輸出是一個list裏包含若干種解法,每種解法是一個String[],起初把每行當做一個String[]了。

Source

public class Solution {
    public List<String[]> solveNQueens(int n) {
        List<String[]> st = new ArrayList<String[]>();
        if(n == 0) return st;
        int[] col = new int[n];
        
        backtrack(n, 0, st, col);

        return st;
    }
    public void backtrack(int n, int row, List<String[]> st, int[] col){
    	if(row == n){
    		String[] temp = new String[n];
    		for(int i = 0; i < n; i++){
    			StringBuffer a = new StringBuffer();
              	for(int j = 0; j < n; j++){
            		if(col[i] == j){ 
            			a.append("Q");
            		}
            		else a.append(".");
            	}
              	temp[i] = a.toString();
            }
    		
    		st.add(temp);
    		return;
    	}
    
    	for(int i = 0; i < n; i++){
    		col[row] = i;
    		
    		if(isValid(row, col)){
    			backtrack(n, row + 1, st, col);
    		}
    		
    	}
    }
    public boolean isValid(int row, int[] col){
    	for(int i = 0; i < row; i++){
    		if(col[i] == col[row] || Math.abs(col[row] - col[i]) == row - i)
    			return false;
    	}
    	return true;
    }
}


Test

   public static void main(String[] args){
    
    	int n = 4;
    
    	List<String[]> st = new Solution().solveNQueens(n);
    	
    	for(int i = 0; i < st.size(); i++){
    		String[] temp = st.get(i);
    		for(int j = 0; j < temp.length; j++){
    			System.out.print(temp[j]);
    		}
    		System.out.println();
    	}
    	
    }





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章