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

机器人的运动范围

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

'''
1.创建rows行cols列的全零矩阵
2.符合threshold条件的矩阵点变成1
3.原点变成2,把与2相邻的点变成2(搜索时2只会向上、向右传播)
4.输出2的个数
'''
class Solution:
    def movingCount(self , threshold: int, rows: int, cols: int) -> int:
        # write code here
        if rows > 79: rows = 79
        if cols > 79: cols = 79
        matrix1 = [[0]*(cols) for i in range(rows)]
        for i in range(rows):
            for j in range(cols):
                sum = i//10 +i%10 +j//10+j%10
                if sum <= threshold:
                    matrix1[i][j] = 1
        counter = 1
        matrix1[0][0] = 2
        for i in range(1,rows):
            if (matrix1[i-1][0] == 2 and matrix1[i][0]==1):
                matrix1[i][0] = 2
                counter += 1
        for j in range(1,cols):
            if (matrix1[0][j-1] == 2 and matrix1[0][j]==1):
                matrix1[0][j] = 2
                counter += 1
        if(cols>1 and rows >1):
            for i in range(1,rows):
                for j in range(1,cols):
                    if (matrix1[i][j] ==1 and (matrix1[i-1][j] ==2 or matrix1[i][j-1] == 2)):
                        matrix1[i][j] =2
                        counter += 1
        return counter

全部评论
以坐标轴来看,原点在左下角;而从矩阵的写法来看,[0][0]元素在左上角。这里说的传播方式是相对坐标轴来看的。
点赞 回复 分享
发布于 2022-03-06 16:01

相关推荐

昨天 10:35
已编辑
西安科技大学 后端
点赞 评论 收藏
分享
sagima:然后这个帖子又登上了
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务