0
点赞
收藏
分享

微信扫一扫

《剑指offer》第13题 机器人的运动范围

一、题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够进入多少个格子?《剑指offer》第13题 机器人的运动范围_二维数组

二、题解

和面试题12类似,方格可以看作一个m*n的矩阵,同样在这个矩阵中,除边界上的格子外,其它格子都有4个相邻的格子。

机器人从坐标(0,0)开始移动,当它准备进入坐标为(i,j)的格子时,通过检查坐标的位数和来判断机器人是否能够进入。如果机器人能够进入坐标为(i,j)的格子,再判断它能否进入4个相邻的格子(i,j-1),(i,j+1),(i-1,j),(i+1,j)。

当进入某个位置时,应当标记这个位置已经访问过,避免之后重复访问,可以设计一个boolean数组,这里设计一个二维数组,也可以通过压缩设计成一维数组来表征一个位置是否被访问过。下面的解答采用二维数组,因为这样记录横纵坐标第i行第j列是否被访问,更为直观。

代码如下:

public class Solution {
    public int movingCount(int threshold, int rows, int cols) {
        if (rows <= 0 || cols <= 0 || threshold < 0)
            return 0;

        boolean[][] isVisited = new boolean[rows][cols];//标记
        int count = movingCountCore(threshold, rows, cols, 0, 0, isVisited);
        return count;
    }

    private int movingCountCore(int threshold,int rows,int cols,
                                int row,int col, boolean[][] isVisited) {
        if (row < 0 || col < 0 || row >= rows || col >= cols || isVisited[row][col]
                || cal(row) + cal(col) > threshold)
            return 0;
        isVisited[row][col] = true;
        return 1 + movingCountCore(threshold, rows, cols, row - 1, col, isVisited)
                + movingCountCore(threshold, rows, cols, row + 1, col, isVisited)
                + movingCountCore(threshold, rows, cols, row, col - 1, isVisited)
                + movingCountCore(threshold, rows, cols, row, col + 1, isVisited);
    }

    private int cal(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
}

举报

相关推荐

0 条评论