趣題集.Leetcode 51(N皇后問題)

n 皇后問題研究的是如何將 n 個皇后放置在 n×n 的棋盤上,而且使皇后彼此之間不能相互攻擊。數組

上圖爲 8 皇后問題的一種解法。

給定一個整數 n,返回全部不一樣的 n 皇后問題的解決方案。bash

每一種解法包含一個明確的 n 皇后問題的棋子放置方案,該方案中 'Q' 和 '.' 分別表明了皇后和空位。app

示例:ui

輸入: 4
輸出: [
 [".Q..",  // 解法 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // 解法 2
  "Q...",
  "...Q",
  ".Q.."]
]
解釋: 4 皇后問題存在兩個不一樣的解法。
複製代碼

PS:字節跳動筆試的時候也遇到了這個題.這裏作個筆記.spa

public class Solution {
    private static final String QUEEN = "Q";
    private static final String SPACE = ".";
    List<List<String>> results = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        /**
         * chess[row] = col, 表示在第row行,第col列放置一個皇后
         */
        int chess[] = new int[n];
        putRow(chess, 0, n);
        return results;
    }

    private void putRow(int chess[], int row, int n) {
        /**
         * 表示最後一行已放了皇后,是一種解法.
         */
        if (row == n) {
            results.add(parseChess(chess, n));
            return;
        }

        /**
         * 構造一個bool數組來標記當前row中那些列不可用
         */
        boolean cols[] = new boolean[n];
        for (int i = 0; i < row; i++) {
            int col = chess[i];
            cols[col] = true;
            int distance = row - i;
            if (col - distance >= 0) cols[col - distance] = true;
            if (col + distance < n) cols[col + distance] = true;
        }

        for (int col = 0; col < n; col++) {
            if (cols[col]) continue;
            chess[row] = col;
            putRow(chess, row + 1, n);
        }
    }

    /**
     * 將一維數組解析爲題目的格式.
     * @param chess
     * @param length
     * @return
     */
    private List<String> parseChess(int chess[], int length) {
        List<String> result = new ArrayList<>();
        for (int row = 0; row < length; row++) {
            StringBuilder sb = new StringBuilder();
            int col = chess[row];
            for (int i = 0; i < length; i++) {
                if (i == col) {
                    sb.append(QUEEN);
                } else {
                    sb.append(SPACE);
                }
            }
            result.add(sb.toString());
        }

        return result;
    }

}
複製代碼
相關文章
相關標籤/搜索