题解 | #机器人的运动范围#

机器人的运动范围

https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8

#include <algorithm>
#include <string>
#include <vector>
class Solution {
public:
    int res=0; 
    int get_str_num(string a){
        int sum=0;
        for(char c : a){
            if (isdigit(c)) {
                int digit = c - '0';
                sum += digit;
            }
        }
        return sum;
        
    }
    
    int max_path_count(int threshold, int rows, int cols, int i, int j, vector<vector<bool>>& matrix){
        
        if((get_str_num(to_string(i))+get_str_num(to_string(j)))>threshold || 
            i<0||i>=rows||j<0||j>=cols|| matrix[i][j]==true){
            return 0;
        }
        res += 1;
        matrix[i][j] = true;
        int a = max_path_count(threshold, rows, cols, i+1,j,matrix);
        int b = max_path_count(threshold, rows,   cols, i-1,j, matrix);
        int c = max_path_count(threshold, rows, cols, i,j-1, matrix);
        int d = max_path_count(threshold, rows, cols, i,j+1, matrix);
        return 0;
    } 
    int movingCount(int threshold, int rows, int cols) {
        if (threshold<=0) {
            return 1;
        }
        vector<vector<bool>> matrix(rows, vector<bool>(cols, false));
        int num = max_path_count(threshold, rows, cols, 0,0, matrix);
        return res;
    }
};

采用深度优先搜索算法,先按照深度把一个分支走到头,再向上一级回溯,直到走完整个矩阵。

全部评论

相关推荐

12-05 18:09
已编辑
广东药科大学 后端工程师
点赞 评论 收藏
分享
11-07 16:07
深圳大学 运营
前端飞升:学长,阿里不是卡双非吗,我深也能去吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务