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

机器人的运动范围

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

  1. 当遇到不可走的时候,务必要return(),否则就会以错误的点为基础继续走下下一个点的(实际这个点都走不到,那继续往下走肯定是错的)
  2. 时时注意索引和x,y的配合
class Solution {
public:
    //位置数组
    int dx[4] = {0,0,-1,1};
    int dy[4] = {-1,1,0,0};

    int cal(int x, int y){
        int sum = 0;
        while(x){
            sum+=x%10;
            x/=10;
        }

        while(y){
            sum+=y%10;
            y/=10;
        }

        return sum;

    }

    void back_trace(int threshold, int row, int col,vector<vector<int>> &visits, int &sum,int rows, int cols){



        //base case 2
        if(cal(row,col)<=threshold){
            sum++;
        }else{
            return;
        }

        visits[row][col] = 1;//标记访问位置

        for(int i = 0; i< 4; i++){

            int newx = col + dx[i];
            int newy = row + dy[i];
            if(newx<0||newx>=cols||newy<0||newy>=rows){
                continue;
            }
            if(visits[newy][newx]==0){
                back_trace(threshold,newy,newx,visits,sum,rows,cols);
            }

        }

    }


    int movingCount(int threshold, int rows, int cols) {
        if(!rows||!cols) return 0;
        vector<vector<int>> visits(rows,vector<int>(cols,0));
        int sum = 0;


        back_trace(threshold,0,0,visits, sum,rows,cols);



        return sum;


    }
};
剑指Offer 文章被收录于专栏

剑指offer的解析结合

全部评论

相关推荐

机械打工仔:第一位颇有孟德之志
点赞 评论 收藏
分享
那一天的Java_Java起来:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
野猪不是猪🐗:我assume that你must技术aspect是solid的,temperament也挺good的,however面试不太serious,generally会feel style上不够sharp
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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