leetCode 30天

题太难了,就来一个N皇后吧
51. N 皇后

cpp 复制代码
class Solution {
private:
    vector<vector<string>> res;
    void backtracking(int n, int row, vector<string>& chessboard){
        if (row == n){
            res.push_back(chessboard);
            return;
        }
        for (int col = 0; col<n; col++){
            if (isValid(row, col, chessboard, n)){
                chessboard[row][col] = 'Q';
                backtracking(n, row+1,chessboard);
                chessboard[row][col] = '.';
            }
        }
    }
    bool isValid(int row, int col, vector<string>& chessboard, int n){
        // 检查列
        for (int i = 0; i<row; i++){
            if (chessboard[i][col] == 'Q'){
                return false;
            }
        }
        // 检查45度角
        for (int i = row-1,j = col-1; i>=0 && j>=0; i--,j--){
            if (chessboard[i][j] == 'Q'){
                return false;
            }
        }
        // 检查135度
        for (int i = row-1,j = col+1; i>=0 && j<n; i--,j++){
            if (chessboard[i][j] == 'Q'){
                return false;
            }
        }
        return true;
    }

public:
    vector<vector<string>> solveNQueens(int n) {
        res.clear();
        vector<string> chessboard(n, string(n,'.'));
        backtracking(n, 0, chessboard);
        return res;
    }
};
相关推荐
Fuxiao___43 分钟前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
Mr_Xuhhh1 小时前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
漫随流水1 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
穿条秋裤到处跑3 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
CoovallyAIHub5 小时前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github
CoovallyAIHub5 小时前
低空安全刚需!西工大UAV-DETR反无人机小目标检测,参数减少40%,mAP50:95提升6.6个百分点
算法·架构·github
CoovallyAIHub5 小时前
IEEE Sensors | 湖南大学提出KGP-YOLO:先定位风电叶片再检测缺陷,三数据集mAP均超87%
算法
Yupureki5 小时前
《算法竞赛从入门到国奖》算法基础:动态规划-路径dp
数据结构·c++·算法·动态规划
副露のmagic6 小时前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展
荣光属于凯撒6 小时前
P2176 [USACO11DEC] RoadBlock S / [USACO14FEB] Roadblock G/S
算法·图论