【DFS】LeetCode 51. N-Queens

LeetCode 51. N-Queens

Solution1:我的答案
回溯法

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string> > res;
        vector<int> temp;
        my_count(res, temp, n);
        return res;
    }

    void my_count(vector<vector<string> >& res, vector<int> temp, int n) { //temp临时答案,num总次数,n棋盘大小
        if (temp.size() == n) {
            my_push(res, temp, n);
            return;
        } else {
            for (int i = 0; i < n; i++) {
                temp.push_back(i);
                if (isValid(temp)) 
                    my_count(res, temp, n);
                temp.pop_back();
            }
        }
    }

    bool isValid(vector<int>& temp) {
        if (temp.size() == 1) return true;
        else {
            int k = temp.size();
            for (int i = 0; i < temp.size() - 1; i++) {
                if(temp[i] == temp[k - 1] || abs(i - k + 1) == abs(temp[i] - temp[k - 1]))
                    return false;
            }
            return true;
        }
    }

    void my_push(vector<vector<string> >& res, vector<int>& temp, int n) {
        string point = "";
        for (int i = 0; i < n; i++) point = point + ".";
        vector<string> temp_str(n, point);
        for (int i = 0; i < n; i++)
            temp_str[i].replace(temp[i], 1, "Q");
        res.push_back(temp_str);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值