54. Spiral Matrix
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
(1) Java
(2) Python
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix or not matrix[0]:
return []
m = len(matrix)
n = len(matrix[0])
rst = []
total = m*n
u, d, l, r = 0, m, 0, n
i, j = 0, 0
while len(rst) < total:
for j in range(l, r):
rst.append(matrix[i][j])
if len(rst) == total:
break
u += 1
for i in range(u, d):
rst.append(matrix[i][j])
if len(rst) == total:
break
r -= 1
for j in range(r-1, l-1, -1):
rst.append(matrix[i][j])
d -= 1
for i in range(d-1, u-1, -1):
rst.append(matrix[i][j])
l += 1
return rst
(3) Scala