python3代码

class Solution:
    def movingCount(self, threshold, rows, cols):
        # write code here
        if not threshold or not rows or not cols:
            return 0
        # 定义每格标志位:  0代表没走过;  1代表走过
        visited = [0]*(rows * cols)
        for row in range(rows):
            for col in range(cols):
                return self.movingCountCore(threshold, rows, cols, row, col, visited)

    # 数字数位求和函数
    def digitSum(self, dig):
        re = 0
        while dig:
            re = re + dig % 10
            dig = dig // 10
        return re

    # 递归回溯判断每步是否可行,并返回计数和累加
    def movingCountCore(self, threshold, rows, cols, row, col, visited):
        count = 0
        if 0 <= row < rows and 0 <= col < cols \
                and self.digitSum(row) + self.digitSum(col) <= threshold \
                and visited[row * cols + col] == 0:
            visited[row * cols + col] = 1
            count = 1 + self.movingCountCore(threshold, rows, cols, row - 1, col, visited) \
                      + self.movingCountCore(threshold, rows, cols, row + 1, col, visited) \
                      + self.movingCountCore(threshold, rows, cols, row, col - 1, visited) \
                      + self.movingCountCore(threshold, rows, cols, row, col + 1, visited)
        return count