BM59 N皇后问题

N皇后问题_牛客题霸_牛客网 (nowcoder.com)

一个N*N的棋盘,要摆放N个皇后 然后这个皇后不能同行、同列、同斜线

 1. 首先重建棋盘:vector<std::string> chessboard(n, std::string(n,'.'));

写成N*N 每个元素都是一个点;

2. 回溯:一行一行的找到合适的位置 放置皇后Q 终止条件是行数到达 此时计数加一


class Solution {
private:
    int res = 0;
    //row 行 col 列
    bool isValid(int row, int col,vector<string>& chessboard,int n){
        // 检查列
        for(int i = 0; i < row ; i++){
            if(chessboard[i][col] == 'Q'){
                return false;
            }
        }
        // 检查 45度角是否有皇后
        for(int i = row - 1, j = col - 1; i >= 0 && j >=0; i--,j--){
            if(chessboard[i][j] == 'Q'){
                return false;
            }
        }
        // 检查 135度角是否有皇后
        for(int i = row - 1 , j = col + 1; i >= 0 && j < n; i--, j++){
            if(chessboard[i][j] == 'Q'){
                return false;
            }
        }
        return true;
    }
    void backtracking(int n, int row,vector<string>& chessboard){
        if(row == n){
            res++;
            return;
        }
        for(int col = 0; col < n; ++col){
            if(isValid(row, col, chessboard, n)){// 验证合法就可以放
                chessboard[row][col] = 'Q';// 放置皇后
                backtracking(n,row+1,chessboard);
                chessboard[row][col] = '.';// 回溯,撤销皇后
            }  
        }
    }
public:
    /**
     * 
     * @param n int整型 the n
     * @return int整型
     */
    int Nqueen(int n) {
        // write code here
        vector<std::string> chessboard(n, std::string(n,'.'));
        backtracking(n,0,chessboard);
        return res;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值