题解 | #机器人的运动范围#

机器人的运动范围

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

# -*- coding:utf-8 -*-
class Solution:
    def movingCount(self, threshold, rows, cols):
        # write code here
        if rows<0&nbs***bsp;cols<0&nbs***bsp;threshold<0:
            return 0
        matrix =[[[]for i in range(cols)]for i in range(rows)]
        count = self.bus(threshold, 0, 0, matrix)
        return count
    
    def bus(self, threshold, rows, cols, matrix):
        if rows < 0&nbs***bsp;cols <0&nbs***bsp;rows >= len(matrix)&nbs***bsp;cols >= len(matrix[0])&nbs***bsp;self.cal(rows)+self.cal(cols) > threshold&nbs***bsp;matrix[rows][cols]:
            return 0
        matrix[rows][cols] = True
        return 1+ self.bus(threshold, rows-1, cols, matrix)+self.bus(threshold, rows+1, cols, matrix)+self.bus(threshold, rows, cols-1, matrix)+self.bus(threshold, rows, cols+1, matrix)
    
    def cal(self, num):
        res = 0
        while num>0:
            res += num%10
            num //= 10
        return res
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务