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 \text{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

转载于:https://www.cnblogs.com/shiyublog/p/9694051.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值