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;
            }
        }
    }
};
相关推荐
myw0712053 小时前
Leetcode94.二叉数的中序遍历练习
c语言·数据结构·笔记·算法
songx_993 小时前
leetcode(填充每个节点的下一个右侧节点指针 II)
java·数据结构·算法·leetcode
chenyuhao20243 小时前
vector深度求索(上)实用篇
开发语言·数据结构·c++·后端·算法·类和对象
minstbe4 小时前
半导体数据分析:GPR算法小白入门(三) 晶体管I-V特性仿真教程
算法
未知陨落5 小时前
LeetCode:60.单词搜索
算法·leetcode
mmz12075 小时前
动态规划 练习(c++)
c++·算法·动态规划
tqs_123456 小时前
分sheet写入excel
开发语言·python·算法
西望云天6 小时前
基础组合计数(三道例题)
数据结构·算法·icpc
小灰灰的FPGA7 小时前
29.9元汉堡项目:基于matlab+FPGA的FFT寻峰算法实现
算法·matlab·fpga开发