13. 机器人的运动方法

机器人的运动范围

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

依然利用回溯法

class Solution:
    def movingCount(self, threshold, rows, cols):
        # write code here
        if threshold < 0 or rows <= 0 or cols <= 0:
            return 0
        visited = [0]*rows*cols
        count = self.movingCountCore(threshold,rows,cols,0,0,visited)
        return count
    def movingCountCore(self,threshold,rows,cols,row,col,visited):
        count = 0 
        if self.check(threshold,rows,cols,row,col,visited):
            visited[row*cols+col] = 1
            count = 1 + self.movingCountCore(threshold,rows,cols,row-1,col,visited)\
            + self.movingCountCore(threshold,rows,cols,row,col-1,visited)\
            + self.movingCountCore(threshold,rows,cols,row+1,col,visited)\
            + self.movingCountCore(threshold,rows,cols,row,col+1,visited)
        return count
    def check(self,threshold,rows,cols,row,col,visited):
        if 0 <= row < rows and 0 <= col < cols and self.getdigitSum(row)+self.getdigitSum(col) <= threshold\
        and not visited[row*cols+col] :
            return True
        return False
    def getdigitSum(self,nums):
        sum = 0
        while nums > 0:
            sum += nums % 10
            nums = nums // 10
        return sum 
全部评论

相关推荐

04-08 16:35
门头沟学院 Java
站队站对牛:实在是恶心的公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务