Matrices
Spiral Matrix
DESCRIPTION (inspired by Leetcode.com)
Write a function to traverse an m x n matrix in spiral order and return all elements in a single list. The traversal should start from the top left corner and proceed clockwise, spiraling inward until every element has been visited.
Input:
matrix = [ [0,1,2], [3,4,5], [6,7,8] ]
Output:
[0,1,2,5,8,7,6,3,4]
Explanation: The elements of the matrix are returned in the order they are visited in a clockwise spiral starting from the top left corner.
Explanation
1. Top Row
def spiral_order(matrix):result = []while matrix:result += matrix.pop(0)if matrix and matrix[0]:for row in matrix:result.append(row.pop())if matrix:result += matrix.pop()[::-1]if matrix and matrix[0]:for row in matrix[::-1]:result.append(row.pop(0))return result
initialize result
0 / 1
2. Right Column
def spiral_order(matrix):result = []while matrix:result += matrix.pop(0)if matrix and matrix[0]:for row in matrix:result.append(row.pop())if matrix:result += matrix.pop()[::-1]if matrix and matrix[0]:for row in matrix[::-1]:result.append(row.pop(0))return result
traverse top row
0 / 2
3. Bottom Row
def spiral_order(matrix):result = []while matrix:result += matrix.pop(0)if matrix and matrix[0]:for row in matrix:result.append(row.pop())if matrix:result += matrix.pop()[::-1]if matrix and matrix[0]:for row in matrix[::-1]:result.append(row.pop(0))return result
traverse right column
0 / 1
4. Left Column
def spiral_order(matrix):result = []while matrix:result += matrix.pop(0)if matrix and matrix[0]:for row in matrix:result.append(row.pop())if matrix:result += matrix.pop()[::-1]if matrix and matrix[0]:for row in matrix[::-1]:result.append(row.pop(0))return result
traverse bottom row
0 / 1
Repeat
def spiral_order(matrix):result = []while matrix:result += matrix.pop(0)if matrix and matrix[0]:for row in matrix:result.append(row.pop())if matrix:result += matrix.pop()[::-1]if matrix and matrix[0]:for row in matrix[::-1]:result.append(row.pop(0))return result
traverse left column
0 / 2
Solution
def spiral_order(matrix):result = []while matrix:result += matrix.pop(0)if matrix and matrix[0]:for row in matrix:result.append(row.pop())if matrix:result += matrix.pop()[::-1]if matrix and matrix[0]:for row in matrix[::-1]:result.append(row.pop(0))return result
spiral matrix
0 / 8
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. We visit each element in the matrix once.
Space Complexity: O(m * n) for the result array that stores all matrix elements.
Mark as read
Your account is free and you can post anonymously if you choose.