机器人的运动范围

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

思路:

深度优先搜索,每搜索到一个满足条件的格子就把该格子的访问位置true,然后再搜索上下左右四个格子,以此类推,

class Solution {
public:
    int movingCount(int threshold, int rows, int cols)
    {
        if(rows<=0 || cols<=0||threshold <0)
            return 0;
        vector<vector<bool>> temp(rows,vector<bool>(cols,false));
        visit = temp;
        thresh = threshold;
        is_true(0,0,rows,cols);
        return count;
    }
      //深度优先搜索,i,j为当前访问的格子坐标,rows和cols为格子的最大行列数
    void is_true(int i,int j,int rows,int cols)
    {
        //如果当前格子的坐标各位数和超过阈值,直接返回,不再搜索
        if(bitsum(i) + bitsum(j) > thresh)
            return;
        //如果格子下标越界,结束搜索
        if(i <0 ||i >= rows ||j < 0|| j >= cols)
            return;
        //当前格子已被访问,不再搜索
        if(visit[i][j] == true)
            return;
        ++count;//当前格子可到达,格子数加1
        visit[i][j] = true;//当前格子访问位置true
        //搜索上下左右四个格子是否可以到达
        is_true(i+1,j,rows,cols);
        is_true(i-1,j,rows,cols);
        is_true(i,j+1,rows,cols);
        is_true(i,j-1,rows,cols);

    }
    //计算坐标各位数之和
    int bitsum(int num)
    {
        int sum =0;
        while(num)
        {
            sum += num%10;
            num = num/10;
        }
        return sum;
    }
private:
    vector<vector<bool>> visit; //访问数组,用来标记哪些格子被访问过,true为已访问过,false为未访问
    int thresh;//threshold值,主要是为了少传一个参数
    int count = 0;//机器人能够到达的格子数
};
原文地址:https://www.cnblogs.com/whiteBear/p/12704362.html