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

总结

回溯法。

相关推荐
gfdhy21 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
Warren981 天前
Python自动化测试全栈面试
服务器·网络·数据库·mysql·ubuntu·面试·职场和发展
百***06011 天前
SpringMVC 请求参数接收
前端·javascript·算法
一个不知名程序员www1 天前
算法学习入门---vector(C++)
c++·算法
云飞云共享云桌面1 天前
无需配置传统电脑——智能装备工厂10个SolidWorks共享一台工作站
运维·服务器·前端·网络·算法·电脑
福尔摩斯张1 天前
《C 语言指针从入门到精通:全面笔记 + 实战习题深度解析》(超详细)
linux·运维·服务器·c语言·开发语言·c++·算法
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——两整数之和
算法·leetcode·职场和发展
Dream it possible!1 天前
LeetCode 面试经典 150_二叉搜索树_二叉搜索树的最小绝对差(85_530_C++_简单)
c++·leetcode·面试
xxxxxxllllllshi1 天前
【LeetCode Hot100----14-贪心算法(01-05),包含多种方法,详细思路与代码,让你一篇文章看懂所有!】
java·数据结构·算法·leetcode·贪心算法
前端小L1 天前
图论专题(二十二):并查集的“逻辑审判”——判断「等式方程的可满足性」
算法·矩阵·深度优先·图论·宽度优先