此题与<<矩阵中的路径>>那一题为同一类问题,方法是采用回溯法来解决,我同样参照剑指offer官方的解释进行了代码实现,思路可以看我<<矩阵中的路径>>的那一题,他们是很相似的哦!!!
如果您看到我的代码有什么问题或者需要改进的请您指正哦!!!!!
class Solution: def movingCount(self, threshold, rows, cols): # write code here if threshold < 0: return 0 visited = [0]*cols*rows result = self.movingCountCore(threshold, 0, 0 ,rows, cols, visited) del visited return result def movingCountCore(self, threshold, row, col ,rows, cols, visited): count = 0 if self.check(threshold, row, col ,rows, cols, visited): visited[row * cols + col] = 1 count = 1 + self.movingCountCore(threshold, row+1, col ,rows, cols, visited)+\ self.movingCountCore(threshold, row-1, col ,rows, cols, visited)+\ self.movingCountCore(threshold, row, col+1 ,rows, cols, visited)+\ self.movingCountCore(threshold, row, col-1 ,rows, cols, visited) return count def check(self, threshold, row, col ,rows, cols, visited): if (row >= 0 and row < rows and col >=0 and col < cols and (not visited[row * cols + col]) and ((self.getDigitSum(row)+self.getDigitSum(col))<=threshold)): return True return False def getDigitSum(self, number): sum_ = 0 for i in str(number): sum_ += int(i) return sum_