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
考點
- 考查對回溯法的理解。通常物體或人在二維方格運動這類問題都可以用回溯法解決。
- 考查對數組編程的能力。一般把矩陣看成一個二維的數組,只有對數組的特性充分了解,纔可能快速、正確實現對回溯代碼編寫。