LintCode N皇后問題

題目

n皇后問題是將n個皇后放置在n*n的棋盤上,皇后彼此之間不能相互攻擊。

給定一個整數n,返回所有不同的n皇后問題的解決方案。

每個解決方案包含一個明確的n皇后放置布局,其中“Q”和“.”分別表示一個女王和一個空位置。

樣例
對于4皇后問題存在兩種解決的方案:

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

 "...Q",

 "Q...",

 "..Q."],

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

 "Q...",

 "...Q",

 ".Q.."]

分析

經典的問題,找出各個可行解。
首先我們判斷怎樣的位置是可行的,也就是不在同一行,不在同一列,且不在對角線上。
自然每個都在不同行上,所以我們可以把問題簡化,在每一行找可以放進皇后的列。

一行一行的找遇到可行的列就加進去,當list的大小等于n的時候,就說明加滿了,可以把結果存進去。

代碼

class Solution {
    /**
     * Get all distinct N-Queen solutions
     * @param n: The number of queens
     * @return: All distinct solutions
     * For example, A string '...Q' shows a queen on forth position
     */
    ArrayList<ArrayList<String>> solveNQueens(int n) {
        ArrayList<ArrayList<String>> results = new ArrayList<>();
        if (n <= 0) {
            return results;
        }
        
        search(results, new ArrayList<Integer>(), n);
        return results;
    }
    
    /*
     * results store all of the chessboards
     * cols store the column indices for each row
     */
    private void search(ArrayList<ArrayList<String>> results,
                        ArrayList<Integer> cols,
                        int n) {
        if (cols.size() == n) {
            results.add(drawChessboard(cols));
            return;
        }
        
        for (int colIndex = 0; colIndex < n; colIndex++) {
            if (!isValid(cols, colIndex)) {
                continue;
            }
            cols.add(colIndex);
            search(results, cols, n);
            cols.remove(cols.size() - 1);
        }
    }
    
    private ArrayList<String> drawChessboard(ArrayList<Integer> cols) {
        ArrayList<String> chessboard = new ArrayList<>();
        for (int i = 0; i < cols.size(); i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < cols.size(); j++) {
                sb.append(j == cols.get(i) ? 'Q' : '.');
            }
            chessboard.add(sb.toString());
        }
        return chessboard;
    }
    
    private boolean isValid(ArrayList<Integer> cols, int column) {
        //cols存儲了每一行Q所在的列
        int row = cols.size();
        
        //不能在同一列,且不能為對象線上的元素
        for (int rowIndex = 0; rowIndex < row; rowIndex++) {
            if (cols.get(rowIndex) == column) {
                return false;
            }
            if (Math.abs(rowIndex - row) == Math.abs(column - cols.get(rowIndex))) {
                return false;
            }
            
        }
        return true;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • n皇后問題是將n個皇后放置在n*n的棋盤上,皇后彼此之間不能相互攻擊。 給定一個整數n,返回所有不同的n皇后問題的...
    鬼谷神奇閱讀 514評論 0 1
  • 題目 根據n皇后問題,現在返回n皇后不同的解決方案的數量而不是具體的放置布局。 樣例比如n=4,存在2種解決方案 代碼
    六尺帳篷閱讀 196評論 0 1
  • 想想我還是把公務員考試中數量關系題跟資料分析題放在一塊說,畢竟都是數學計算題。數量關系,說白了就是小學奧...
    織夢學生閱讀 713評論 0 0
  • 前情回顧:契約游戲 小說目錄 游戲一開局,這便注定是一場不公平的賭局,我沒壓抵上任何籌碼,輸了,依舊毫發無傷,而你...
    原小尚閱讀 662評論 7 2
  • 站在時間交替的節點,回顧過去一年,這是大學畢業以后收獲最多的一年,感謝這一年的收獲,它是成長路上不可或缺的閱歷。感...
    dream2024閱讀 266評論 7 4