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

机器人的运动范围

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

class Solution:
    def movingCount(self, threshold: int, rows: int, cols: int) -> int:
        # write code here
        '''
        1.创建rows行cols列的全零矩阵
        2.calc_thre()函数,str int 实现题目条件
        3.count()函数,计数获取矩阵内1的个数
        4.dfs()函数,not vis[x][y]是指该坐标为0,经过坐标设为1,for循环遍历路径,返回count()函数
        注:机器人可以选择返回经过的路径,用dfs的话需要让它遍历所有的路径,也就是加上for循环
        '''
        vis = [[0] * cols for _ in range(rows)]
        def calc_thre(x, y):
            ans = 0
            for i in str(x):
                ans += int(i)
            for i in str(y):
                ans += int(i)
            return ans <= threshold

        def count():
            num = 0
            for i in range(rows):
                for j in range(cols):
                    if vis[i][j] == 1:
                        num += 1
            return num

        def dfs(x, y):
            if 0 <= x < rows and 0 <= y < cols and not vis[x][y] and calc_thre(x, y):
                vis[x][y] = 1
                for i in range(4):
                    dfs(x, y + 1) or dfs(x, y - 1) or dfs(x + 1, y) or dfs(x - 1, y)
                return count()
            return 0

        return dfs(0, 0)
               

全部评论

相关推荐

07-02 13:52
武汉大学 golang
骗你的不露头也秒
牛客87776816...:😃查看图片
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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