Skip to content

Commit b07905b

Browse files
committed
Spiral Matrix
1 parent 816e349 commit b07905b

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

054-spiral-matrix.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/spiral-matrix/
3+
4+
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
5+
6+
Example 1:
7+
Input:
8+
[
9+
[ 1, 2, 3 ],
10+
[ 4, 5, 6 ],
11+
[ 7, 8, 9 ]
12+
]
13+
Output: [1,2,3,6,9,8,7,4,5]
14+
15+
Example 2:
16+
Input:
17+
[
18+
[1, 2, 3, 4],
19+
[5, 6, 7, 8],
20+
[9,10,11,12]
21+
]
22+
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
23+
"""
24+
class Solution(object):
25+
def spiralOrder(self, matrix):
26+
"""
27+
:type matrix: List[List[int]]
28+
:rtype: List[int]
29+
"""
30+
if matrix == []:
31+
return []
32+
top = left = 0
33+
bottom = len(matrix) - 1
34+
right = len(matrix[0]) - 1
35+
direction = 0
36+
res = []
37+
while top <= bottom and left <= right:
38+
if direction == 0:
39+
for i in range(left,right+1):
40+
res.append(matrix[top][i])
41+
top += 1
42+
elif direction == 1:
43+
for i in range(top,bottom+1):
44+
res.append(matrix[i][right])
45+
right -= 1
46+
elif direction == 2:
47+
for i in range(right,left-1,-1):
48+
res.append(matrix[bottom][i])
49+
bottom -= 1
50+
elif direction == 3:
51+
for i in range(bottom, top-1, -1):
52+
res.append(matrix[i][left])
53+
left += 1
54+
direction = (direction+1) % 4
55+
return res

0 commit comments

Comments
 (0)