Learn DSA
Depth-First Search
Greedy Algorithms
Spiral Matrix
DESCRIPTION (credit 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:
Output:
Explanation: The elements of the matrix are returned in the order they are visited in a clockwise spiral starting from the top left corner.
💻 Desktop Required
The code editor works best on larger screens. Please open this page on your computer to write and run code.
Given an `m x n` matrix, return all elements of the matrix in spiral order. For example, given the following matrix: ``` [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` The output should be `[1,2,3,6,9,8,7,4,5]`.
Run your code to see results here
Have suggestions or found something wrong?
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
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.
Login to track your progress
Your account is free and you can post anonymously if you choose.