剑指offer13

剑指offer13

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

思路:对数 x 每次对 10 取余,就能知道数 x 的个位数是多少,然后再将 x 除 10,这个操作等价于将 x 的十进制数向右移一位,删除个位数,不断重复直到 x 为 0 时结束。

class Solution {
    
    //深度优先遍历
    public int movingCount(int m, int n, int k) {
    
    
        if(k == 0){
    
    
            return 1;
        }
        //使用数组存储队列信息
        Queue <int[]> queue = new LinkedList<>();
        // 向右和向下的方向数组
        int [] x = {
    
    0,1};
        int [] y = {
    
    1,0};
        boolean [][] arr  = new boolean[m][n];
        queue.offer(new int []{
    
    0,0});//添加元素
        arr[0][0] = true;//定义为true
        int count = 1;//记录能够到达的格子数
        while(!queue.isEmpty()){
    
    
            int [] arr2 = queue.poll();//返回第一个元素,并在队列中删除
            int xm = arr2[0], yn = arr2[1];
            for(int i = 0; i < 2; i ++){
    
    
                int tx = x[i] + xm;//
                int ty = y[i] + yn;
                if (tx < 0 || tx >= m || ty < 0 || ty >= n || arr[tx][ty] || get(tx) + get(ty) > k) {
    
    
                    continue;//循环
                }
                    queue.offer(new int []{
    
    tx,ty});//将符合的格子元素放入到数组中
                    queue.offer(new int []{
    
    tx, ty});
                    arr[tx][ty] = true;
                    count++;
                }
            }
            return count;
        }
    
        private int get(int x) {
    
    //找出行坐标和列坐标的数位之和大于k的格子
        int res = 0;
        while (x != 0) {
    
    
            res += x % 10;
            x /= 10;
        }
        return res;
    }
}

时间复杂度:O(mn)

猜你喜欢

转载自blog.csdn.net/qq_52230126/article/details/121458666