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;
            }
        }
    }
};
相关推荐
布莱克6054 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
D e re k ZH7 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
石小石Orz8 小时前
AI 正在蚕食我们的编码能力
前端·后端·算法
民乐团扒谱机9 小时前
【微实验】NSGA-II(非支配排序遗传算法)——解决多目标优化问题的“自然选择模拟器”
linux·人工智能·算法
青少儿编程课堂9 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中缀表达式求值解析
c++·python·算法·bfs·信息学竞赛
文丑颜不良啊10 小时前
LeetCode2261~2280题目解析
java·leetcode
武子康11 小时前
Qwen-Drive 到底是什么:4B 级 VLM 如何成为驾驶策略底座
人工智能·算法·机器学习
zh_xuan13 小时前
LeeCode 496. 下一个更大元素I
数据结构·算法·栈·单调栈
机 _ 长13 小时前
05 智算运维|8 张卡怎么才算「捆成一张」:NCCL 实测与拓扑
运维·人工智能·算法·智算运维