1. 程式人生 > >[LeetCode] N-Queens N皇后問題

[LeetCode] N-Queens N皇后問題

問題:

測試資料:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]


優化   -- 剪枝:

思路:


對角線分析:

 

程式碼;

import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class liubobo_8_6 {
/// 51. N-Queens
/// https://leetcode.com/problems/n-queens/description/
/// 時間複雜度: O(n^n)
/// 空間複雜度: O(n)
    private boolean[] col;//列方向是否衝突
    private boolean[] dia1;//左對角線是否衝突
    private boolean[] dia2;//右對角線是否衝突
    private ArrayList<List<String>> res;

    public List<List<String>> solveNQueens(int n) {

        res = new ArrayList<List<String>>();
        col = new boolean[n];
        dia1 = new boolean[2 * n - 1];
        dia2 = new boolean[2 * n - 1];

        LinkedList<Integer> row = new LinkedList<Integer>();
        putQueen(n, 0, row);

        return res;
    }

    // 嘗試在一個n皇后問題中, 擺放第index行的皇后位置
    private void putQueen(int n, int index, LinkedList<Integer> row){

        if(index == n){//遞迴函式終止情況
            res.add(generateBoard(n, row));
            return;
        }

        for(int i = 0 ; i < n ; i ++)
            // 嘗試將第index行的皇后擺放在第i列
            if(!col[i] && !dia1[index + i] && !dia2[index - i + n - 1]){
                row.addLast(i);
                col[i] = true;// i列不能再有元素了
                dia1[index + i] = true;//index +i對角線中不能再有元素了
                dia2[index - i + n - 1] = true;//index- i + n - 1對角線中不能再有元素了
                putQueen(n, index + 1, row);
                col[i] = false;//回溯
                dia1[index + i] = false;// 回溯
                dia2[index - i + n - 1] = false;// 回溯
                row.removeLast();//回溯
            }

        return;
    }
    //將row的解轉換為二維陣列的解
    private List<String> generateBoard(int n, LinkedList<Integer> row){

        assert row.size() == n;

        ArrayList<String> board = new ArrayList<String>();
        for(int i = 0 ; i < n ; i ++){
            char[] charArray = new char[n];
            Arrays.fill(charArray, '.');
            charArray[row.get(i)] = 'Q';
            board.add(new String(charArray));
        }
        return board;
    }

    private static void printBoard(List<String> board){
        for(String s: board)
            System.out.println(s);
        System.out.println();
    }

    public static void main(String[] args) {

        int n = 4;
        List<List<String>> res = (new liubobo_8_6()).solveNQueens(n);
        for(List<String> board: res)
            printBoard(board);
    }
}

類似問題;

1. Sudoku Solver 求解數獨