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 小时前
[创业之路-682]:实即虚,虚即实。真正的技术壁垒,藏在光路之外、电路之下、代码之中。
人工智能·算法·系统架构·制造·创业·产业链
2401_841495643 小时前
【计算机视觉】霍夫变换检测
图像处理·人工智能·python·opencv·算法·计算机视觉·霍夫变换
半桶水专家3 小时前
C语言中的setitimer函数详解
c语言·开发语言·算法
FS_tar4 小时前
高斯消元矩阵
c++·算法·矩阵
小蝙蝠侠4 小时前
安德烈·卡帕西:深入探索像ChatGPT这样的大语言模型内容列表
人工智能·算法·机器学习
闻缺陷则喜何志丹5 小时前
【贪心之临项交换】P8732 [蓝桥杯 2020 国 ABC]|普及
c++·算法·蓝桥杯·贪心·洛谷
而后笑面对5 小时前
关于力扣2025.10.4每日 11.盛最多雨水的容器
算法·leetcode·职场和发展
UrbanJazzerati5 小时前
考研数学:数轴根法(穿根法)——高效求解高次不等式的利器
算法
可触的未来,发芽的智生5 小时前
新奇特:负权重橡皮擦,让神经网络学会主动遗忘
人工智能·python·神经网络·算法·架构