JZ13 机器人的运动范围
机器人的运动范围
https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&tqId=23460&ru=/practice/2a49359695a544b8939c77358d29b7e6&qru=/ta/coding-interviews/question-ranking
# -*- coding:utf-8 -*- 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_