20200411——剑指offer 面试题13:机器人运动的范围

package question13_机器人运动范围;

/**
 * @Classname Main
 * @Description TODO
 * @Date 2020/4/11 16:47
 * @Created by mmz
 */
public class Main {

    static int Moving(int threshold,int rows,int cols){
        if(threshold<0|| rows<0||cols<0){
            return 0;
        }
        boolean[] visit = new boolean[rows*cols];

        int count =  Core(threshold,rows,cols,0,0,visit);
        return count;
    }

    static int Core(int threshold,int rows,int cols,int i ,int j,boolean[] visit){
        int count = 0;
        if(cheak(threshold,rows,cols,i,j,visit)){
            visit[j*rows+i] = true;
            count = 1+Core(threshold,rows,cols,i+1,j,visit)
                    +Core(threshold,rows,cols,i-1,j,visit)
                    +Core(threshold,rows,cols,i,j+1,visit)
                    +Core(threshold,rows,cols,i,j-1,visit);
        }
        return count;
    }
    static boolean cheak(int threshold,int rows,int cols,int i ,int j,boolean[] visit){
        if(!visit[j*rows+i] && i>=0 &&i<rows &&j>=0 && j<cols && getDigit(i)+getDigit(j) <=threshold){
            return true;
        }
        return false;
    }

    static int getDigit(int i){
        int sum = 0;
        while(i>0){
            sum += i%10;
            i /=10;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(Moving(18, 40, 40));
    }
}

有四个函数
第一个为启动函数
第二个为核心函数
第三个、四个都是辅助函数
第三个用来判断是否能进入该点,第四个用来当前位置的各位数和是否小于等于阻拦的位置。

核心函数来判断从(x,y)来是遍历。每次进入格子要更新当前布尔类型数组visit,最后用深度遍历遍历整个放格,返回能去到的个数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值