LeetCode刷题_c++版-51N皇后

class Solution {
    
    
public:
	//放置皇后
    void putDownMark(int x, int y, vector<vector<int>> &mark){
    
    
        //方向数组,8个方向
        static const int dx[]={
    
    1,1,0,-1,-1,-1,0,1};
        static const int dy[]={
    
    0,1,1,1,0,-1,-1,-1};
        mark[x][y] = 1;
        //8个方向所有位置都变成1
        for(int i = 0; i<mark.size(); i++){
    
    
            for(int j  = 0; j<8; j++){
    
    
                int new_x = x+i*dx[j];
                int new_y = y+i*dy[j];
                if(new_x<mark.size() && new_x >= 0 && new_y<mark.size()&& new_y>=0){
    
    
                    mark[new_x][new_y] = 1;
                }
            }
        }


    }

    void generate(vector<vector<int>> mark, vector<string> location,vector<vector<string>> &result, int i){
    
    
        //放到最后一行了,说明这个放法可以放置成功
        if(i == mark.size()){
    
    
            result.push_back(location);
            return;
        }
        //每一行尝试所有位置
        for(int j=0; j<mark.size();j++){
    
    
            if(mark[i][j] == 0){
    
    
                vector<vector<int>> tmp_mark = mark;
                putDownMark(i,j,mark);
                location[i][j] = 'Q';
                generate(mark,  location, result, i+1);
                //if(statute == 1) return;
                //回溯,方便继续判断下一个位置
                mark = tmp_mark;
                location[i][j] = '.';
                
            }
        }
    }
    
    vector<vector<string>> solveNQueens(int n) {
    
    
        //皇后规则,在某点放置了皇后,则它可以吃前后左右、左上、右上、左下、右下任意多步的棋子
        //n*n的棋盘放n个皇后,则每行都得放一个
        vector<string> location;
        vector<vector<string>> result;
        vector<vector<int>> mark;
        vector<int> tmp;
        //vector<string> tmp1;
        //int statute = 0;
        //初始化mark数组
        for(int i = 0;i <n;i++){
    
    
            mark.push_back(tmp);
            //location.push_back(tmp1);
            //location[i].push_back("");
            for(int j = 0; j<n ;j++)
                mark[i].push_back(0);
            location.push_back("");
            location[i].append(n,'.') ;
            //cout<<i;
        }

        generate(mark, location,result, 0);
        return result;


    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44343355/article/details/128843459