LeetCode #51 -  N-Queens

本文详细解析了N皇后问题的算法实现,通过回溯法在N×N的棋盘上放置N个皇后,使得任意两个皇后都不会互相攻击。示例代码展示了如何返回所有可能的解决方案配置。

题目描述:

The n-queens puzzle is the problem of placing n queens on an n×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:

Input: 4

Output: [

 [".Q..",  // Solution 1

  "...Q",

  "Q...",

  "..Q."],

 ["..Q.",  // Solution 2

  "Q...",

  "...Q",

  ".Q.."]

]

Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> result;
        vector<int> pos(n,-1);
        NQueens(result,pos,0);
        return result;
    }
    
    // row表示当前行,pos存储之前所有行的皇后所在的列数
    void NQueens(vector<vector<string>>& result, vector<int> pos, int row)
    {
        int n=pos.size();
        for(int i=0;i<n;i++)
        {
            pos[row]=i; // 对于当前行,尝试所有可能的列数
            bool isValid=true;
            for(int j=0;j<row;j++)
            {
                if(pos[row]==pos[j]||pos[row]-pos[j]==row-j||pos[row]-pos[j]==j-row)
                {
                    isValid=false;
                    break;
                }
            }
            if(isValid)
            {
                if(row==n-1)
                {
                    vector<string> v;
                    for(int j=0;j<n;j++)
                    {
                        string temp(n,'.');
                        temp[pos[j]]='Q';
                        v.push_back(temp);
                    }
                    result.push_back(v);
                }
                else NQueens(result,pos,row+1);
            }
        }
    }
};

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值