剑指offer 机器人的运动范围

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

同样是一个图的搜索的问题,深度搜索递归即可

其中自己定义个函数计算数位之和

public int movingCount(int threshold, int rows, int cols)
    {
        boolean[] flag = new boolean[rows * cols];
        helperMovingCount(threshold,rows,cols,0,0,flag);
        int count = 0;
        for(boolean b : flag){
            if(b) count++;
        }
        return count;
    }

    public void helperMovingCount(int threshold,int rows, int cols, int r, int c,boolean[] flag ){
        int index = r * cols + c ;
        if(r >= rows || r < 0 || c >= cols || c< 0 || sumTwoShuweiNum(r,c) > threshold || flag[index]) return;
        flag[index] = true;
        helperMovingCount(threshold,rows,cols,r,c+1,flag);
        helperMovingCount(threshold,rows,cols,r,c-1,flag);
        helperMovingCount(threshold,rows,cols,r+1,c,flag);
        helperMovingCount(threshold,rows,cols,r-1,c+1,flag);
    }



    public int sumTwoShuweiNum(int n1, int n2) {
        return shuweiNum(n1)+shuweiNum(n2);
    }
    public int shuweiNum(int num) {
        int sum = 0;
        while(num != 0){
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }

猜你喜欢

转载自blog.csdn.net/ymybxx/article/details/79936426