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;
    }
}

总结

回溯法。

相关推荐
夏鹏今天学习了吗2 小时前
【LeetCode热题100(82/100)】单词拆分
算法·leetcode·职场和发展
mit6.8243 小时前
mysql exe
算法
2501_901147833 小时前
动态规划在整除子集问题中的应用与高性能实现分析
算法·职场和发展·动态规划
中草药z3 小时前
【嵌入模型】概念、应用与两大 AI 开源社区(Hugging Face / 魔塔)
人工智能·算法·机器学习·数据集·向量·嵌入模型
CCPC不拿奖不改名4 小时前
SQL基础(SQL小白教程):MySQL语句+环境一键搭建+面试习题
数据库·sql·计算机网络·mysql·oracle·面试·职场和发展
踩坑记录4 小时前
leetcode hot100 189.轮转数组 medium
leetcode
知乎的哥廷根数学学派4 小时前
基于数据驱动的自适应正交小波基优化算法(Python)
开发语言·网络·人工智能·pytorch·python·深度学习·算法
ADI_OP4 小时前
ADAU1452的开发教程10:逻辑算法模块
算法·adi dsp中文资料·adi dsp·adi音频dsp·adi dsp开发教程·sigmadsp的开发详解
xingzhemengyou14 小时前
C语言 查找一个字符在字符串中第i次出现的位置
c语言·算法
Dream it possible!5 小时前
LeetCode 面试经典 150_二分查找_在排序数组中查找元素的第一个和最后一个位置(115_34_C++_中等)
c++·leetcode·面试