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

机器人的运动范围

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

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param threshold int整型 
# @param rows int整型 
# @param cols int整型 
# @return int整型
#
class Solution:
    def cal_sum(self, i):
        s = 0
        while i:
            s += i%10
            i //= 10
        return s

    def move(self, i, j, threshold, state, rows, cols):
        if self.cal_sum(i) + self.cal_sum(j) <= threshold:
            self.nums += 1
            if i > 0 and state[i-1][j] == 0:
                state[i-1][j] = 1
                self.move(i-1, j, threshold, state, rows, cols)
            if i < rows - 1 and state[i+1][j] == 0:
                state[i+1][j] = 1
                self.move(i+1, j, threshold, state, rows, cols)
            if j > 0 and state[i][j-1] == 0:
                state[i][j-1] = 1
                self.move(i, j-1, threshold, state, rows, cols)
            if j < cols - 1 and state[i][j+1] == 0:
                state[i][j+1] = 1
                self.move(i, j+1, threshold, state, rows, cols)
        return

    def movingCount(self , threshold: int, rows: int, cols: int) -> int:
        # write code here
        self.nums = 0
        state = [[0 for _ in range(cols)] for _ in range(rows)]
        state[0][0] = 1
        self.move(0, 0, threshold, state, rows, cols)
        return self.nums

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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