欢迎光临散文网 会员登陆 & 注册

这就是传说中的N皇后? 回溯算法安排!| LeetCode:51.N皇后

2023-09-09 19:14 作者:那我来问你  | 我要投稿

按顺序看下来,到这里能自己做出来了!贴一个c++

class Solution {

public:

    vector<vector<string>> res;

    vector<vector<int>> pos;

    int n;

    string s="";


    void draw(){

        vector<string> t_res(n, s);

        for (auto p: pos){

            t_res[p[0]][p[1]] = 'Q';

        }

        res.push_back(t_res);

    }


    bool is_legal(int x, int y){

        int dx, dy;

        for (auto p: pos){

            dx = abs(x-p[0]), dy = abs(y-p[1]);

            if (dx == 0 || dy == 0 || dx == dy) {

                return false;

            }

        }

        return true;

    }


    void backtracking(int idx){

        if (pos.size() == n){

            draw();

            return;

        }

        for (int i=idx; i<n; ++i){

            for (int j=0; j<n; ++j){

                if (is_legal(i, j)){

                    pos.push_back({i, j});

                    backtracking(i+1);

                    pos.pop_back();

                }

            }

            if (pos.size()-1 != i) break;

        }

    }


    vector<vector<string>> solveNQueens(int n) {

        this->n = n;

        for (int i=0; i<n; ++i) s+='.';

        backtracking(0);

        return res;

    }

};

这就是传说中的N皇后? 回溯算法安排!| LeetCode:51.N皇后的评论 (共 条)

分享到微博请遵守国家法律