码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 54. Spiral Matrix & 59. Spiral Matrix II

时间:2018-09-24 00:51:47      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:can   nts   5.7   ted   order   rect   return   ext   else   

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

Leetcode 54. Spiral Matrix & 59. Spiral Matrix II

标签:can   nts   5.7   ted   order   rect   return   ext   else   

原文地址:https://www.cnblogs.com/shiyublog/p/9694051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!