【算法三十七】51. N 皇后

51. N 皇后

回溯:

java 复制代码
class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> ans = new ArrayList<>();
        //每一行的queen在哪一列
        int[] queens = new int[n];
        //每一列有没有重复
        boolean[] col = new boolean[n];
        //主对角线有没有重复
        boolean[] dig1 = new boolean[2*n-1];
        //副对角线有没有重复
        boolean[] dig2 = new boolean[2*n-1];

        dfs(0,queens,col,dig1,dig2,ans);
        return ans;
    }

    private void dfs(int r,int[] queens,boolean[] col,boolean[] dig1,boolean[] dig2,List<List<String>> ans){
        int n = col.length;
        if(r == n){
            List<String> partAns = new ArrayList<>();
            for(int i:queens){
                char[] partAns1 = new char[n];
                Arrays.fill(partAns1,'.');
                partAns1[i] = 'Q';
                partAns.add(new String(partAns1));
            }
            ans.add(partAns);
            return;
        }
        //对列遍历
        for(int c = 0;c<n;c++){
            //对副对角线的规律加上n-1这样符合下标规律
            int rc = r-c + n-1;
            if(!col[c] && !dig1[r+c] && !dig2[rc]){
                queens[r] = c;
                col[c] = dig1[r+c] = dig2[rc] = true;
                //递归
                dfs(r+1,queens,col,dig1,dig2,ans);
                //恢复现场
                col[c] = dig1[r+c] = dig2[rc] = false;
            }
        }
    }
}

时间复杂度:O(N^2 * N!)

空间复杂度:O(N)

相关推荐
稚南城才子,乌衣巷风流35 分钟前
ST 表(Sparse Table)算法详解:原理、实现与应用
算法
hold?fish:palm41 分钟前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle1 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木1 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
不会就选b2 小时前
算法日常・每日刷题--<归并排序>1
数据结构·算法
危桥带雨2 小时前
排序算法(快排、归并、计数、基数排序)
数据结构·算法·排序算法
啦啦啦啦啦zzzz2 小时前
算法:回溯算法
c++·算法·leetcode
IT探索2 小时前
Linux 查找文件指令总结
linux·算法
Lumos1863 小时前
51单片机从零到实战(完结)——后续学习路线建议
算法