机器人的运动范围

机器人的运动范围

题目:

地上有一个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。请问该机器人能够到达多少个格子?

示例 1:
输入:m = 2, n = 3, k = 1
输出:3

示例 2:
输入:m = 3, n = 1, k = 0
输出:1

dfs:

class Solution {

    private boolean[][] book;
    private int[][] next = new int[][]{{0, 1}, {1, 0}};

    public int movingCount(int m, int n, int k) {
        int ans = 0;
        book = new boolean[m][n];
        return dfs(m, n, k, 0, 0);
    }

    private int dfs(int m, int n, int k, int x, int y) {
        if(x >= m || y >= n || getSum(x) + getSum(y) > k || book[x][y]) {
            return 0;
        }

        book[x][y] = true;
        int sum = 1;
        for(int i = 0; i < 2; i++) {
            sum += dfs(m, n, k, x + next[i][0], y + next[i][1]);
        }

        return sum;
    }

    private int getSum(int x) {
        int sum = 0;
        while(x != 0) {
            sum += x % 10;
            x /= 10;
        }

        return sum;
    }
}

bfs:

class Solution {

    private boolean[][] book;
    private int[][] next = new int[][]{{0, 1}, {1, 0}};

    public int movingCount(int m, int n, int k) {
        book = new boolean[m][n];
        Queue<int[]> queue = new LinkedList();
        queue.offer(new int[]{0, 0});
        book[0][0] = true;
        int ans = 1;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                int arr[] = queue.poll();
                for(int j = 0; j < 2; j++) {
                    int tx = arr[0] + next[j][0];
                    int ty = arr[1] + next[j][1];
                    if(tx >= m || ty >= n || book[tx][ty] || getSum(tx) + getSum(ty) > k) {
                        continue;
                    }

                    book[tx][ty] = true;
                    ans++;
                    queue.offer(new int[]{tx, ty});
                }
            }
        }

        return ans;
    }

    private int getSum(int x) {
        int sum = 0;
        while(x != 0) {
            sum += x % 10;
            x /= 10;
        }

        return sum;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值