zoukankan      html  css  js  c++  java
  • leetcode54 Spiral Matrix

     1 """
     2 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
     3 Example 1:
     4 Input:
     5 [
     6  [ 1, 2, 3 ],
     7  [ 4, 5, 6 ],
     8  [ 7, 8, 9 ]
     9 ]
    10 Output: [1,2,3,6,9,8,7,4,5]
    11 Example 2:
    12 Input:
    13 [
    14   [1, 2, 3, 4],
    15   [5, 6, 7, 8],
    16   [9,10,11,12]
    17 ]
    18 Output: [1,2,3,4,8,12,11,10,9,5,6,7]
    19 """
    20 class Solution:
    21     def spiralOrder(self, matrix):
    22         if not matrix:
    23             return []
    24         res = []
    25         row_end = len(matrix)-1
    26         col_end = len(matrix[0])-1
    27         row_begin, col_begin = 0, 0
    28         while row_begin <= row_end and col_begin <= col_end:#!!!关键
    29             # 向右
    30             j = col_begin
    31             while j <= col_end:
    32                 res.append(matrix[row_begin][j])
    33                 j += 1
    34             row_begin += 1
    35             # 向下
    36             i = row_begin
    37             while i <= row_end:
    38                 res.append(matrix[i][col_end])
    39                 i += 1
    40             col_end -= 1
    41             if row_begin <= row_end:
    42             # 向左
    43                 j = col_end
    44                 while j >= col_begin:
    45                     res.append(matrix[row_end][j])
    46                     j -= 1
    47             row_end -= 1
    48             if col_begin <= col_end:
    49             # 向上
    50                 i = row_end
    51                 while i >= row_begin:
    52                     res.append(matrix[i][col_begin])
    53                     i -= 1
    54             col_begin += 1
    55         return res
  • 相关阅读:
    C++ 中的深入浅拷贝和深拷贝
    C++ 引用小问题
    6-10
    6-8
    6-7
    6-4
    6-3
    6-1
    5-31
    COMException 依赖服务或组无法启动(0x8007042C)处理办法
  • 原文地址:https://www.cnblogs.com/yawenw/p/12489060.html
Copyright © 2011-2022 走看看