LeetCode:62.N皇后

目录

1.N皇后


1.N皇后

对于N皇后这道题,可以用标志数组来表示这列,主对角线,副对角线是否能存放皇后,那么如何用一个通式来描述

我们发现每主对角线都符合y = x + b,所以可以写为y - x = b, 但是对于边界的几点例如(1,0)减出来为负数,所以可以统一加上皇后数n来保证正数,所以可以写为y - x + n = b + n,

而副对角线符合y = -x + b, 写为y + x = b即可

cpp 复制代码
class Solution {
    bool checkcol[10], checkdig1[20], checkdig2[20];
    vector<vector<string>> ret;
    vector<string> path;
    int n;
public:
    vector<vector<string>> solveNQueens(int _n) 
    {
        n = _n;
        path = vector<string>(n, string(n, '.'));
        dfs(0);
        return ret;
    }

    void dfs(int row)
    {
        if(row == n)
        {
            ret.push_back(path);
            return;
        }
        for(int col = 0; col < n; col++)
        {
            if(checkcol[col] == false && checkdig1[row - col + n] == false && checkdig2[row + col] == false)
            {
                path[row][col] = 'Q';
                checkcol[col] = checkdig1[row - col + n] = checkdig2[row + col] = true;
                dfs(row + 1);
                path[row][col] = '.';
                checkcol[col] = checkdig1[row - col + n] = checkdig2[row + col] = false;
            }
        }
    }
};
相关推荐
起个名字费劲死了8 分钟前
VisionMaster集成深度学习算法(基础狗)
人工智能·深度学习·算法
lengxuenong11 分钟前
枚举例题分析
c++·算法·青少年编程
Navigator_Z29 分钟前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
2601_9657422232 分钟前
短视频脚本创作方法分享:本地生活类账号的起步思路
大数据·人工智能·算法·ai·新媒体运营·生活
55873生态系统手记41 分钟前
读完 55873 资产钱包的技术栈,我重新理解了 "合规钱包" 应该长什么样
算法·架构
旋生万物44 分钟前
素数螺旋映射 $z_n=n^{1+i}$ 的角分布统计检验与零模型对比
大数据·前端·人工智能·算法·云原生·螺旋生成论·螺旋相位
HRTOS1 小时前
HRTOS Shell继续完善:优化printf缓冲区与字符串越界保护,国庆后随新版本更新
运维·单片机·嵌入式硬件·算法·51单片机
邵奈一1 小时前
当沉香之乡遇上 Seed-2.1-pro:我用 AI 给村子做了一个数字门面
算法·架构
海天一色y1 小时前
图像分割全解析:从经典算法到深度学习的原理与实战(Python + MATLAB)
python·深度学习·算法
垆边人似月.2 小时前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode