66 机器人的运动范围

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
 
思路:利用一个访问数组,以及访问的位置就设置为true,结合一个判断合法的if语句,不合法的情况就返回0,相当于可以回退,找到所有可以到达的位置
 
class Solution {
public:
    bool isvalid(int threshold,int x,int y){
        int sum = 0;
        while(x != 0){
            sum += x % 10;
            x = x / 10;
        }
        while(y != 0){
            sum += y % 10;
            y = y / 10;
        }
        if(sum > threshold){
            return false;
        }
        return true;
    }
    
    int helper(int threshold, int rows, int cols,vector<bool> &visited,int startx,int starty){
        if(startx < 0 || starty < 0 || startx >= rows || starty >= cols || !isvalid(threshold,startx,starty) || visited[startx * cols + starty]){
            return 0;//不合法的情况,有加1减一,所以要和0以及上限比较
        }
        visited[startx * cols + starty] = true;//访问的位置设置为已访问,这样判断不合法的时候,下次就返回0,不会重复计算
        return helper(threshold,rows,cols,visited,startx,starty - 1) +
               helper(threshold,rows,cols,visited,startx,starty + 1) +
               helper(threshold,rows,cols,visited,startx - 1,starty) +
               helper(threshold,rows,cols,visited,startx + 1,starty) + 1;//上下左右访问,进入到这里的说明可以加1(之前没访问)
            
    }
    
    int movingCount(int threshold, int rows, int cols){
       if(threshold <= 0 || rows <= 0 || cols <= 0){ 
           return 0;
       }
       int res = 0;
       vector<bool> visited(rows * cols,false);
       res = helper(threshold,rows,cols,visited,0,0);
       return res;        
    }
};

 

posted @ 2018-02-28 10:20  zqlucky  阅读(190)  评论(0)    收藏  举报