【回溯】【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;
    }
}
相关推荐
海绵宝宝转agent9 天前
LeetCode100 二叉树个人题解
算法·leetcode·深度优先
CQU_JIAKE10 天前
10.31[A]
算法·深度优先
海绵宝宝转agent11 天前
LeetCodehot100题解
java·笔记·学习·算法·leetcode·深度优先
海绵宝宝转agent12 天前
Leetcode二叉树算法个人理解
笔记·学习·算法·leetcode·深度优先
海绵宝宝转agent13 天前
Leetcode100+面经
java·笔记·学习·算法·leetcode·深度优先
mjhcsp14 天前
Code date creation v8.0 竞赛数据生成与对拍实战指南
算法·ai·深度优先·cdc
wdfk_prog14 天前
LWIP教程 40:从 `socket()` 到 `lwip_socket()`——DFS fd、SAL Socket 与 lwIP Backend
算法·深度优先
NEFU_Jyj18 天前
牛客周赛R166(max型瓶颈最短路,前后缀DP合并)
算法·深度优先
?abc!20 天前
(动态规划+DFS)494. 目标和
算法·深度优先·动态规划
INGNIGHT22 天前
815 · 课程表IV(dfs)
算法·深度优先