Spiral matrix#
Practice Link#
LeetCode
Description#
- Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Examples#
1Input:
2[
3 [ 1, 2, 3 ],
4 [ 4, 5, 6 ],
5 [ 7, 8, 9 ]
6]
7Output: [1,2,3,6,9,8,7,4,5]
1Input:
2[
3 [1, 2, 3, 4],
4 [5, 6, 7, 8],
5 [9,10,11,12]
6]
7Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Python Solution#
1def spiralOrder(self, matrix):
2 res = []
3 while matrix:
4 res.extend(matrix.pop(0)) # left to right
5 if matrix and matrix[0]: # top to dwon
6 for row in matrix:
7 res.append(row.pop())
8 if matrix: # right to left
9 res.extend(matrix.pop()[::-1])
10 if matrix and matrix[0]: # bottom to up
11 for row in matrix[::-1]:
12 res.append(row.pop(0))
13 return res