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;
            }
        }
    }
};
相关推荐
文丑颜不良啊31 分钟前
LeetCode51~75题目解析
leetcode
高晶35 分钟前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy38 分钟前
大数计算思路
算法
高晶1 小时前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗1 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李1 小时前
反向传播计算梯度举例
算法
niyongsheng1 小时前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
302wanger2 小时前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法
lisw053 小时前
微分与积分的本质区别解析
算法·数学建模·极限编程
xys_6783 小时前
深挖数据结构:树和二叉树(上)
数据结构·算法