LeetCode 51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

Example 1:

复制Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above

Example 2:

Input: n = 1
Output: [["Q"]]

Constraints:

1 <= n <= 9

实现思路:

不多赘述了,本博客在DFS分类里有三道N皇后问题,总结就是回溯算法。

AC代码:

class Solution {
    vector<vector<string>> ans;
    vector<string> sq;
    int col[100],dg[100],udg[100];
    void dfs(int x,int size){
        if(x==size){
            ans.push_back(sq);
            return;
        }
        for(int i=0;i<size;i++){
            if(!col[i]&&!dg[x+i]&&!udg[size-x+i]){
                sq[x][i]='Q';//放皇后
                col[i]=dg[x+i]=udg[size-x+i]=1;
                dfs(x+1,size);                
                col[i]=dg[x+i]=udg[size-x+i]=0;
                sq[x][i]='.';
            }
        }
    } 
    
public:
    vector<vector<string>> solveNQueens(int n) {
        string tag;
        for(int i=0;i<n;i++) tag+='.';
        for(int i=0;i<n;i++) sq.push_back(tag);//初始化
        cout<<sq.size();
        dfs(0,n);
        return ans;
    }
};
posted @   coderJ_ONE  阅读(32)  评论(0)    收藏  举报
编辑推荐:
· 长文讲解 MCP 和案例实战
· Hangfire Redis 实现秒级定时任务,使用 CQRS 实现动态执行代码
· Android编译时动态插入代码原理与实践
· 解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
· 通过一个DEMO理解MCP(模型上下文协议)的生命周期
阅读排行:
· 工良出品 | 长文讲解 MCP 和案例实战
· 多年后再做Web开发,AI帮大忙
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· centos停服,迁移centos7.3系统到新搭建的openEuler
· 上周热点回顾(4.14-4.20)
点击右上角即可分享
微信分享提示