zoukankan      html  css  js  c++  java
  • LeetCode 54. 螺旋矩阵

    给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
    
    示例 1:
    输入:
    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    输出: [1,2,3,6,9,8,7,4,5]
    
    示例 2:
    输入:
    [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9,10,11,12]
    ]
    输出: [1,2,3,4,8,12,11,10,9,5,6,7]
    
    class Solution:
        def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
            if not matrix:
                return []
            rows, columns = len(matrix), len(matrix[0])
            left, right, top, bottom = 0, columns - 1, 0, rows - 1  # 四个顶点
            ans = []
            while True:
                for col in range(left, right + 1):            ## 上
                    ans.append(matrix[top][col])
                top+=1
                if top > bottom: break
    
                for row in range(top, bottom + 1):             ## 右
                    ans.append(matrix[row][right])
                right-=1
                if left > right: break 
    
                for col in range(right, left-1, -1):           ## 下
                    ans.append(matrix[bottom][col])
                bottom-=1
                if top > bottom: break 
    
                for row in range(bottom, top - 1, -1):         ## 左
                    ans.append(matrix[row][left])
                left+=1
                if left > right: break
            return ans
    
  • 相关阅读:
    解题:NOI 2007 社交网络
    解题:2018九省联考 一双木棋
    125. 背包问题 II
    152. 组合
    140. 快速幂
    148. 颜色分类
    144. 交错正负数
    83. 落单的数 II
    124. 最长连续序列
    59. 最接近的三数之和
  • 原文地址:https://www.cnblogs.com/sandy-t/p/13423857.html
Copyright © 2011-2022 走看看