Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created October 18, 2018 19:11
Show Gist options
  • Save yokolet/09361e7f6e2837597ad0c9da30ef4c51 to your computer and use it in GitHub Desktop.
Save yokolet/09361e7f6e2837597ad0c9da30ef4c51 to your computer and use it in GitHub Desktop.
Spiral Matrix
"""
Description:
Given a matrix of m x n elements (m rows, n columns), return all elements of the
matrix in spiral order.
Examples:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
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]
"""
def spiralOrder(matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix: return []
m, n = len(matrix), len(matrix[0])
startRow, endRow = 0, m-1
startCol, endCol = 0, n-1
result = []
count = m * n
while startRow <= endRow and startCol <= endCol:
for i in range(startCol, endCol+1):
result.append(matrix[startRow][i])
count -= 1
if count == 0: break
startRow += 1
for i in range(startRow, endRow+1):
result.append(matrix[i][endCol])
count -= 1
if count == 0: break
endCol -= 1
for i in range(endCol, startCol-1, -1):
result.append(matrix[endRow][i])
count -= 1
if count == 0: break
endRow -= 1
for i in range(endRow, startRow-1, -1):
result.append(matrix[i][startCol])
count -= 1
if count == 0: break
startCol += 1
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment