剑指offer 13 - 机器人的运动范围 - python

58 阅读1分钟

题目描述:

地上有一个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

提示:

  • 1 <= n,m <= 100
  • 0 <= k <= 20

思路

这道题和矩阵中的路径是类似的问题,所以我们同样可以采用相同的方法进行解决,不同之处在于中间的判断有些不同。

  • 首先根据给定的行数和列数构建方格矩阵
  • 递归遍历判断走过的格子是否满足阈值条件,由于这里不是寻找一条连续的路径,而只是判断某个格子是否满足要求,因此递归条件相对更简单一些。只要满足格子位于矩阵中、当前格子满足条件以及当前格子并没有被访问过这三个条件就可以
  • 最后统计满足条件的格子数即可

对于题目中的阈值判断条件可以使用python内置的map函数对xy中的元素分别转换成整数再相加,判断相加的和是否不超过给定阈值即可。

sum(map(int, str(i) + str(j)))

或者对坐标按位取数字相加,如下所示:

 def judge(self, threshold, i, j):
        def helper(x):
            t = 0
            while x > 0:
                t += x % 10
                x = x // 10
            return t 
        
        return True if helper(i) + helper(j) <= threshold else False

完整的解题代码:

#coding=utf-8
class Solution:
    def judge(self, threshold, i, j):
        if sum(map(int, str(i) + str(j))) <= threshold:
            return True
        else:
            return False
 
    def findgrid(self, threshold, rows, cols, matrix, i, j):
        count = 0
        if i < rows and j < cols and i >= 0 and j >= 0 and self.judge(threshold, i, j) and matrix[i][j] == 0: 
        
            matrix[i][j] = 1  
            count = 1 + self.findgrid(threshold, rows, cols, matrix, i, j + 1) \
            + self.findgrid(threshold, rows, cols, matrix, i, j - 1) \
            + self.findgrid(threshold, rows, cols, matrix, i + 1, j) \
            + self.findgrid(threshold, rows, cols, matrix, i - 1, j)
        return count
 
    def movingCount(self, threshold, rows, cols):
        # 首先根据给定的rows和cols构建矩阵
        matrix = [[0 for i in range(cols)] for j in range(rows)]
        # 统计能达到的格子数,从(0,0)开始
        count = self.findgrid(threshold, rows, cols, matrix, 0, 0)
        return count