代码随想录打卡Day30 | 回溯算法part06

心得:

N皇后:std::vector<std::string> path(n, std::string(n, '.'));构造一个由'.'组成的字符串。



第一题、重新安排形成 LeetCode332 (没做)

第二题、N皇后 LeetCode https://leetcode.cn/problems/n-queens/

 

n皇后问题是回溯算法解决的经典问题,但是用回溯解决多了组合、切割、子集、排列问题之后,遇到这种二维矩阵还会有点不知所措。

首先来看一下皇后们的约束条件:

  1. 不能同行
  2. 不能同列
  3. 不能同斜线

确定完约束条件,来看看究竟要怎么去搜索皇后们的位置,其实搜索皇后的位置,可以抽象为一棵树。

下面我用一个 3 * 3 的棋盘,将搜索过程抽象为一棵树,如图:

51.N皇后

 

一行一行的试不同的位置。因此可以用row == n作为终止条件。判断位置是否合法的isValid函数中,只需要判断已有的列,45度角和135度角有没有元素。

class Solution {
public:
    vector<vector<string>> res;

    void backtracking(int n, int row, vector<string>& path){
        if(row == n){
            res.push_back(path);
            return;
        }
        //for(int col = 0; col <= row;)
        for(int col = 0; col < n; col++){
            if(isValid(n, row, col, path)){
                path[row][col] = 'Q';
                //backtracking(n, row, path);
                backtracking(n, row + 1, path);
                path[row][col] = '.';
            }
        }
        return;
    }

    bool isValid(int n, int row, int col, vector<string>& path){
        for(int i = 0; i < row; i++){//检查列
            if(path[i][col] == 'Q') return false;
        }
        for(int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--){//检查45度
            if(path[i][j] == 'Q') return false;
        }
        //for(int i = col - 1, j = row + 1; i >= 0 && j >= 0; i--, j++){//检查135度
        for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++){//检查135度
            if(path[i][j] == 'Q') return false;
        }
        return true;
    }
    
    vector<vector<string>> solveNQueens(int n) {
        res.clear();
        std::vector<std::string> path(n, std::string(n, '.'));
        backtracking(n, 0, path);
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值