当前位置 : 主页 > 网页制作 > HTTP/TCP >

leetcode 51 N皇后问题(回溯法)

来源:互联网 收集:自由互联 发布时间:2021-06-16
#includemath.h class Solution { private : vector string solution; vector vector int result; vector int columns; public : bool check( int row, int col){ for ( int r= 0 ; rrow; r++ ) if (columns[r] == col || (row-r) == abs(columns[r]- col)) r

#include<math.h>
class Solution {
private:
    vector<string> solution;
    vector< vector <int>> result;
    vector<int> columns;
public:
    bool check(int row, int col){
        for(int r=0; r<row; r++)
            if(columns[r] == col || (row-r) == abs(columns[r]-col))
                return false;
        return true;
    }
    void backtracking(int n, int row){
        if(row == n){
            result.push_back(columns);
            return;
        }  
        for(int col=0; col<n; col++){
            columns.push_back(col);
            if(check(row, col))
                backtracking(n, row+1);
            columns.pop_back();
        }
    }
    vector<vector<string>> solveNQueens(int n) {
        backtracking(n, 0);
        vector<vector<string>> res;
        for(auto &v:result){
            vector<string> s;
            for(auto &c:v){
                string t(n, .);
                t[c] = Q;
                s.push_back(t);
            }
            res.push_back(s);
        }
        return res;
    }
};

解题方法借鉴https://leetcode-cn.com/problems/n-queens/solution/c-hui-su-fa-by-da-li-wang-4/

网友评论