动态规划编程题螺旋矩阵python解法

  • class Solution:def spiralMatrixIII(self, rows, cols, rStart, cStart):# 初始化结果列表并将起始位置加入结果res = [(rStart, cStart)]
  •     # 如果结果列表的长度等于总的单元格数,直接返回结果
        if rows * cols == 1:
            return res
    
        # 初始化步长和方向
        step = 1
        dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]  # 右、下、左、上
        r, c = rStart, cStart
        di = 0  # 当前方向索引
        
        # 循环直到结果列表的长度等于总的单元格数
        while len(res) < rows * cols:
            # 遍历当前步长,移动相应的次数
            for _ in range(step):
                # 更新当前位置
                r += dirs[di][0]
                c += dirs[di][1]
                
                # 如果当前位置在网格范围内,加入结果列表
                if 0 <= r < rows and 0 <= c < cols:
                    res.append((r, c))
            
            # 改变移动方向
            di = (di + 1) % 4
            
            # 每两次改变方向后,步长加1
            if di == 0 or di == 2:
                step += 1
    
        return res
    
    

    示例输入

    rows = 5cols = 6rStart = 1cStart = 4

    创建Solution对象并调用方法

    solution = Solution()result = solution.spiralMatrixIII(rows, cols, rStart, cStart)print(result)

    #动态规划#
    全部评论

    相关推荐

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