python官方题解--机器人的运动范围

机器人的运动范围

http://www.nowcoder.com/questionTerminal/6e5207314b5241fb83f2329e89fdecc8

此题与<<矩阵中的路径>>那一题为同一类问题,方法是采用回溯法来解决,我同样参照剑指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_
全部评论

相关推荐

点赞 评论 收藏
分享
秋招之BrianGriffin:你再跟他说华为工资也低(相对互联网)就可以享受私信爆炸了😋
点赞 评论 收藏
分享
评论
5
收藏
分享

创作者周榜

更多
正在热议
更多
牛客网
牛客企业服务