feat(54-spiral-matrix): add py3 solution
This commit is contained in:
parent
a8ffbb4c5d
commit
3465499ac9
20
0054_spiral-matrix/README.md
Normal file
20
0054_spiral-matrix/README.md
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
|
||||||
|
|
||||||
|
Example 1:
|
||||||
|
|
||||||
|
![](https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg)
|
||||||
|
|
||||||
|
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
|
||||||
|
|
||||||
|
Example 2:
|
||||||
|
|
||||||
|
![](https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg)
|
||||||
|
|
||||||
|
Input: matrix = [[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]
|
||||||
|
|
||||||
|
Constraints:
|
||||||
|
|
||||||
|
* `m == matrix.length`
|
||||||
|
* `n == matrix[i].length`
|
||||||
|
* `1 <= m, n <= 10`
|
||||||
|
* `-100 <= matrix[i][j] <= 100`
|
41
0054_spiral-matrix/python3/solution.py
Normal file
41
0054_spiral-matrix/python3/solution.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
class Solution:
|
||||||
|
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
|
||||||
|
row_begin_loc, row_end_loc = 0, len(matrix) - 1
|
||||||
|
col_begin_loc, col_end_loc = 0, len(matrix[0]) - 1
|
||||||
|
result = []
|
||||||
|
|
||||||
|
while row_begin_loc <= row_end_loc and col_begin_loc <= col_end_loc:
|
||||||
|
# Top Side
|
||||||
|
i, j = row_begin_loc, col_begin_loc
|
||||||
|
while j <= col_end_loc:
|
||||||
|
result.append(matrix[i][j])
|
||||||
|
j += 1
|
||||||
|
|
||||||
|
# Right Side
|
||||||
|
i += 1
|
||||||
|
j -= 1
|
||||||
|
while i <= row_end_loc:
|
||||||
|
result.append(matrix[i][j])
|
||||||
|
i += 1
|
||||||
|
|
||||||
|
# Bottom Side
|
||||||
|
i -= 1
|
||||||
|
j -= 1
|
||||||
|
while j >= col_begin_loc and i > row_begin_loc:
|
||||||
|
result.append(matrix[i][j])
|
||||||
|
j -= 1
|
||||||
|
|
||||||
|
# Left Side
|
||||||
|
i -= 1
|
||||||
|
j += 1
|
||||||
|
while i > row_begin_loc and j < col_end_loc:
|
||||||
|
result.append(matrix[i][j])
|
||||||
|
i -= 1
|
||||||
|
|
||||||
|
row_begin_loc += 1
|
||||||
|
row_end_loc -= 1
|
||||||
|
col_begin_loc += 1
|
||||||
|
col_end_loc -= 1
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
Loading…
Reference in New Issue
Block a user