LeetCode第51题 - N 皇后

题目

解答

java 复制代码
class Solution {
    public List<List<String>> solveNQueens(int n) {
        int[][] chestPanel = new int[n][n];
        for (int i = 0; i < n; ++i) {
            Arrays.fill(chestPanel[i], 0);
        }
        List<List<String>> results = new ArrayList<>();

        solveNQueens(n, results, chestPanel, 0);

        return results;
    }

    public void solveNQueens(int n, List<List<String>> results, int[][] chestPanel, int row) {
        if (row == n) {
            List<String> lines = new ArrayList<>();
            for (int i = 0; i < n; ++i) {
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < n; ++j) {
                    if (chestPanel[i][j] == 1) {
                        sb.append("Q");
                    } else {
                        sb.append(".");
                    }
                }
                lines.add(sb.toString());
            }
            results.add(lines);
            return;
        }

        for (int i = 0; i < n; ++i) {
            if (isValidPosition(chestPanel, row, i)) {
                chestPanel[row][i] = 1;
                solveNQueens(n, results, chestPanel, row + 1);
                chestPanel[row][i] = 0;
            } else {
                chestPanel[row][i] = 0;
            }
        }
    }


    public boolean isValidPosition(int[][] chestPanel, int currentRow, int currentColomn) {

        int n = chestPanel.length;
        if (currentColomn >= n || currentRow >= n) {
            return false;
        }
        // 当前列
        for (int i = 0; i < currentRow; ++i) {
            if (chestPanel[i][currentColomn] == 1) {
                return false;
            }
        }

        // 左上角
        for (int i = currentRow - 1, j = currentColomn - 1; i >= 0 && j >= 0; --i, --j) {
            if (chestPanel[i][j] == 1) {
                return false;
            }
        }
        // 右上角
        for (int i = currentRow - 1, j = currentColomn + 1; i >= 0 && j < n; --i, ++j) {
            if (chestPanel[i][j] == 1) {
                return false;
            }
        }

        return true;
    }
}

总结

回溯法。

相关推荐
Savior`L几秒前
字符串哈希
c++·算法·哈希算法·散列表
啊阿狸不会拉杆2 分钟前
《数字图像处理》实验3-频率域处理方法
图像处理·人工智能·算法·计算机视觉·数字图像处理
代码游侠7 分钟前
应用——HTTP天气查询
网络·笔记·网络协议·算法·http
智航GIS12 分钟前
6.1 for循环
开发语言·python·算法
爱学大树锯15 分钟前
353 · 最大字母」
算法
YGGP16 分钟前
【Golang】LeetCode 416. 分割等和子集
算法·leetcode
wjykp20 分钟前
part4 反向传播算法(BP算法)
人工智能·算法·机器学习
AndrewHZ21 分钟前
【图像处理基石】图像处理领域还有哪些核心挑战与难题?
图像处理·人工智能·算法·计算机视觉·噪声·图像增强·画质增强
啊阿狸不会拉杆21 分钟前
《数字图像处理》实验8-图像识别与分类
图像处理·人工智能·算法·分类·数据挖掘·数字图像处理
月明长歌25 分钟前
【码道初阶】Leetcode138:随机链表的复制:用 HashMap 做深拷贝的标准解法
java·数据结构·算法·leetcode·链表·哈希算法