机器人的运动范围——jzoffer

题目:地上有一个m x n的方格矩阵。一个机器人从坐标(0, 0)的格子开始移动,它每次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格(35, 37),因为3+5+3+7=18。但它不能进入方格(35, 38),因为数位之和大于了18。请问该机器人能够到达多少个格子?

class Solution:
    
    def check_cell(self, r, c, threshold):
        num = 0
        while r > 0 or c > 0:
            num = num + r % 10 + c % 10
            r = r / 10
            c = c / 10
        return num <= threshold
            
    def count_cells(self, matrix, rows, cols):
        if not matrix or rows <= 0 or cols <= 0:
            raise Exception("something wrong")
        count = self.moving_count(matrix, rows, cols, 0, 0)
        return count
    
    def moving_count(self, matrix, rows, cols, r, c, visited=None):
        if not visited:
            visited = {(r, c): 0 for r in range(rows) for c in range(cols)}
        count = 0
        if r >= 0 and r < rows and c >= 0 and c < cols and not visited[(r, c)] \
           and self.check_cell(r, c):
            visited[(r, c)] = 1
            count = 1 + self.moving_count(matrix, rows, cols, r+1, c, visited)\
                    + self.moving_count(matrix, rows, cols, r-1, c, visited)\
                    + self.moving_count(matrix, rows, cols, r, c+1, visited)\
                    + self.moving_count(matrix, rows, cols, r, c-1, visited)
        return count

你可能感兴趣的:(机器人的运动范围——jzoffer)