【面试题13】机器人的运动范围

【面试题13】机器人的运动范围_第1张图片
Python题解
这题和12题思路一样,都是回溯法的使用。

class Solution:
    def movingCount(self, threshold, rows, cols):
        if threshold < 0 or rows < 0 or cols < 0: return 0
        visited = [False] * (rows * cols)
        def getDigitSum(num):
            count_sum = 0
            while num != 0:
                count_sum += num % 10
                num = num // 10
            return count_sum
        def check(rows, cols, row, col, threshold, visited):
            if row >=0 and row < rows and col >= 0 and col < cols \
                and getDigitSum(row)+getDigitSum(col) <= threshold\
                and not visited[row*cols+col]:
                return True
            return False
        def helper(rows, cols, row, col, threshold, visited):
            count = 0
            if check(rows, cols, row, col, threshold, visited):
                visited[row*cols+col] = True
                count = 1 + helper(rows, cols, row-1, col, threshold, visited)+ \
                helper(rows, cols, row+1, col, threshold, visited)+ \
                helper(rows, cols, row, col-1, threshold, visited)+ \
                helper(rows, cols, row, col+1, threshold, visited)
            return count
        res = helper(rows, cols, 0, 0, threshold, visited)
        return res

考点

  • 考查对回溯法的理解。通常物体或人在二维方格运动这类问题都可以用回溯法解决。
  • 考查对数组编程的能力。一般把矩阵看成一个二维的数组,只有对数组的特性充分了解,才可能快速、正确实现对回溯代码编写。

你可能感兴趣的:(朱滕威的面试之路)