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
考点