zoukankan      html  css  js  c++  java
  • Leetcode 54. Spiral Matrix & 59. Spiral Matrix II

    54. Spiral Matrix [Medium]

    Description

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    Example 1:

    Input:
    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]
    

    Example 2:

    Input:
    [
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9,10,11,12]
    ]
    Output: [1,2,3,4,8,12,11,10,9,5,6,7]

    Solution

    Approach 1. 按照外围圈遍历

    用r标记圈数(r = 0开始),同时(r, r)也为起始坐标。

    注意:

    对于 [6 7],避免再次回转到6,应加入判断条件:m > 1

    对于[7

            8

            9] 避免再次回转到7,应加入判断条件:n > 1

     1 class Solution:
     2     def spiralOrder(self, matrix):
     3         """
     4         :type matrix: List[List[int]]
     5         :rtype: List[int]
     6         """
     7         r = 0
     8         ret = []
     9         if not matrix or not matrix[0]:
    10             return ret
    11         m, n = len(matrix), len(matrix[0])
    12         while m >= 1 and n >= 1:
    13             for i in range(n):
    14                 ret.append(matrix[r][r + i])
    15             for i in range(m - 1):
    16                 ret.append(matrix[r + 1 + i][r + n - 1])
    17             
    18             if m > 1:
    19                 for i in range(n - 1):
    20                     ret.append(matrix[r + m - 1][r + n - 1 - 1 - i])
    21             if n > 1:
    22                 for i in range(m - 2):
    23                     ret.append(matrix[r + m - 1 -1 - i][r])
    24             m -= 2
    25             n -= 2
    26             r += 1
    27         return ret

    Beats: 75.70%

    Runtime: 36ms

    Approach 2. Simulation

    参考Leetcode官方Solution

    Intuition

    Draw the path that the spiral makes. We know that the path should turn clockwise whenever it would go out of bounds or into a cell that was previously visited.

    Algorithm

    Let the array have R rows and C columns. seen[r][c] denotes that the cell on the r-th row and c-th column was previously visited.

    Our current position is (r, c), facing direction  ext{di}di, and we want to visit R x C total cells.

    As we move through the matrix, our candidate next position is (cr, cc).

    If the candidate is in the bounds of the matrix and unseen, then it becomes our next position;

    otherwise, our next position is the one after performing a clockwise turn.

     1 class Solution:
     2     def spiralOrder(self, matrix):
     3         """
     4         :type matrix: List[List[int]]
     5         :rtype: List[int]
     6         """
     7         if not matrix: return []
     8         R, C = len(matrix), len(matrix[0])
     9         seen = [[False] * C for _ in matrix]
    10         ans = []
    11         dr = [0, 1, 0, -1]
    12         dc = [1, 0, -1, 0]
    13         r = c = di = 0
    14         
    15         for _ in range(R * C):
    16             ans.append(matrix[r][c])
    17             seen[r][c] = True
    18             cr, cc = r + dr[di], c + dc[di]
    19             if 0 <= cr < R and 0 <= cc < C and not seen[cr][cc]:
    20                 r, c = cr, cc
    21             else:
    22                 di = (di + 1) % 4
    23                 r, c = r + dr[di], c + dc[di]
    24         return ans

    Beats: 75.70%

    Runtime: 36ms

    59. Spiral Matrix II [Medium]

    Description

    Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    Example:

    Input: 3
    Output:
    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]

    Solution

    用r标记圈数
    1    2   3   | 4
    --------      |
    12| 13 14 | 5
    11| 16 15 | 6
    10|  9   8    7
          ------------

    注意当n == 1时,for循环中n - 1 = 0,则不能执行,
    如input = 3 时,9不能输出,
    所以需要单独写 n == 1 时的情况。

     1 class Solution:
     2     def generateMatrix(self, n):
     3         """
     4         :type n: int
     5         :rtype: List[List[int]]
     6         """
     7         matrix = [([0] * n) for _ in range(n)]
     8         cnt = 1
     9         r = 0
    10         while n >= 2:
    11             for i in range(n - 1):
    12                 matrix[r][r + i] = cnt
    13                 cnt += 1
    14             for i in range(n - 1):
    15                 matrix[r + i][r + n - 1] = cnt
    16                 cnt += 1
    17             for i in range(n - 1):
    18                 matrix[r + n - 1][r + n - 1 - i] = cnt
    19                 cnt += 1
    20             for i in range(n - 1):
    21                 matrix[r + n - 1 - i][r] = cnt
    22                 cnt += 1
    23 
    24             n -= 2
    25             r += 1
    26         if n == 1:
    27             matrix[r][r] = cnt
    28         return matrix

    Beats: 48.93%

    Runtime: 44ms

  • 相关阅读:
    Serverless 工程实践 | Serverless 应用开发观念的转变
    如何高效学习 Kubernetes 知识图谱?
    互动赠新书|当云原生遇到混合云:如何实现“求变”与“求稳”的平衡
    5 款阿里常用代码检测工具,免费用!
    AI与传统编译器
    OpenArkCompiler方舟编译
    传统编译原理
    LLVM基础技术图例
    双极型与低频大功率晶体管
    TVM,Relay,Pass
  • 原文地址:https://www.cnblogs.com/shiyublog/p/9694051.html
Copyright © 2011-2022 走看看