【回溯】【DFS】51.N皇后

题目

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

        return res;
    }

    public void dfs(char[][] tmp, int layer, List<List<String>> res) {
        int n = tmp.length;
        if (layer == n) {
            List<String> solu = new ArrayList<>();
            for (int k = 0; k < n; ++k) {
                solu.add(String.valueOf(tmp[k]));
            }
            res.add(solu);
            return;
        }
        for (int k = 0; k < n; ++k) {
            if (isValid(tmp, layer, k)) {
                tmp[layer][k] = 'Q';
                dfs(tmp, layer + 1, res);
                tmp[layer][k] = '.';
            }
        }
    }

    boolean isValid(char[][] tmp, int x, int y) {
        int n = tmp.length;
        for (int i = 0; i < n; ++i) {
            if (tmp[i][y] == 'Q' && i < x) {
                return false;
            }
        }
        int i = 1;
        while (x - i >= 0 && y - i >= 0) { 
            if (tmp[x - i][y - i] == 'Q') {
                return false;
            }
            ++i;
        }
        i = 1;
        while (x - i >= 0 && y + i < n) {
            if (tmp[x - i][y + i] == 'Q') {
                return false;
            }
            ++i;
        }
        
        return true;
    }
}
相关推荐
山峰哥3 天前
数据库工程与查询优化案例深度复盘‌
数据库·sql·oracle·编辑器·深度优先·宽度优先
血小板要健康3 天前
网格 dfs 与 FloodFill:从岛屿、区域到搜索路径
笔记·算法·leetcode·深度优先
山峰哥4 天前
数据库工程:Explain执行计划对比调优实战‌
大数据·数据库·sql·编辑器·深度优先
lch2011_yb5 天前
CSP-J 2022 上升点列 题解
算法·深度优先
老洋葱Mr_Onion7 天前
【C++】CSP-J初赛模拟卷七错题整理(作者自用)
c++·算法·深度优先
Nil2087 天前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
珂朵莉MM7 天前
2026国信杯具身智能创新大赛-编程技能赛--本科组国赛解题报告 | 珂学家
算法·深度优先·图论
Nil2087 天前
leetcode 199二叉树的右视图
算法·leetcode·深度优先
zander2588 天前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
qq_419563099 天前
ToT 的 BFS/DFS 有个致命缺口:蒙特卡洛树搜索(MCTS)用「随机试错+统计」让大模型想得更深,小模型 + 它竟超过 GPT-4
算法·深度优先·宽度优先