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

题目

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

你可能感兴趣的:(力扣Top100,深度优先,N皇后)