解法1:利用回溯法解决!
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
self.rows = rows
self.cols = cols
self.count = 0
self._dict ={}
self.patrol(threshold, 0, 0)
return self.count
def patrol(self,threshold, row, col):
if row >= 0 and row < self.rows and col >= 0 and col < self.cols:
if row%10+row//10+col//10+col%10 <= threshold:
if self._dict.get((row,col)) is not None:
return
self._dict[(row,col)] = 1
self.count += 1
self.patrol(threshold,row+1,col)
self.patrol(threshold,row-1,col)
self.patrol(threshold,row,col+1)
self.patrol(threshold,row,col-1)