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

总结

回溯法。

相关推荐
gugugu.19 分钟前
算法:滑动窗口类型题目的总结
算法·哈希算法
大数据张老师1 小时前
数据结构——直接插入排序
数据结构·算法·排序算法·1024程序员节
hoiii1871 小时前
基于SVM与HOG特征的交通标志检测与识别
算法·机器学习·支持向量机
进击的炸酱面1 小时前
第四章 决策树
算法·决策树·机器学习
爱coding的橙子1 小时前
每日算法刷题Day81:10.29:leetcode 回溯5道题,用时2h
算法·leetcode·职场和发展
大千AI助手2 小时前
Householder变换:线性代数中的镜像反射器
人工智能·线性代数·算法·决策树·机器学习·qr分解·householder算法
Mr.H01272 小时前
迪杰斯特拉(dijkstra)算法
算法
南方的狮子先生2 小时前
【数据结构】从线性表到排序算法详解
开发语言·数据结构·c++·算法·排序算法·1024程序员节
派大星爱吃猫2 小时前
快速排序和交换排序详解(含三路划分)
算法·排序算法·快速排序·三路划分
焜昱错眩..2 小时前
代码随想录第四十八天|1143.最长公共子序列 1035.不相交的线 53. 最大子序和 392.判断子序列
算法·动态规划