LeetCode面试题13. 机器人的运动范围

面试题13. 机器人的运动范围 题目链接

解题思路:从坐标 ( 0 ,0 ) 开始向右、下遍历,判断是否满足规则(坐标位数之和不大于 k),且未被访问。

满足要求则运动范围 count++,继续遍历;不满足,则返回上一有效坐标,进行有效遍历。

private int[] moveX = {1, 0},
            moveY = {0, 1};
    private int count = 0;
    public int movingCount(int m, int n, int k) {
        boolean[][] visited = new boolean[m][n];
        recursion(m, n, k, 0, 0, visited);
        return count;
    }

    private void recursion(int m, int n, int k, int curX, int curY, boolean[][] visited) {
        if (curX >= m || curX < 0 ||
                curY >= n || curY < 0 ||
                visited[curX][curY] ||
                sumOfDigits(curX) + sumOfDigits(curY) > k) {
              return;
        }
        count++;
        visited[curX][curY] = true;
        for (int i = 0; i < moveX.length; i++) {
            int tempX = curX + moveX[i], tempY = curY + moveY[i];
            recursion(m, n, k, tempX, tempY, visited);
        }
    }
    
    private int sumOfDigits(int nums) {
        int sum = 0;
        while (nums != 0) {
            sum += nums % 10;
            nums /= 10;
        }
        return sum;
    }

解法二:动态规划,递推公式,当前坐标可访问性=上方坐标可访问性 OR 左方坐标可访问性

思路参考:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof/solution/ji-qi-ren-de-yun-dong-fan-wei-by-leetcode-solution/

class Solution {
    public int movingCount(int m, int n, int k) {
        int count = 0;
        boolean[][] visited = new boolean[m][n];
        visited[0][0] = true;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i - 1 >= 0) {
                    visited[i][j] |= visited[i - 1][j];
                }
                if (j - 1 >= 0) {
                    visited[i][j] |= visited[i][j - 1];
                }
                if (visited[i][j] && sumOfDigits(i) + sumOfDigits(j) <= k) {
                    count++;
                } else {
                    visited[i][j] = false;
                } 
            }
        }
        return count;
    }
    
    private int sumOfDigits(int nums) {
        int sum = 0;
        while (nums != 0) {
            sum += nums % 10;
            nums /= 10;
        }
        return sum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值