Spiral Matrix
Given a matrix of m x n
elements (m
rows, n
columns), return all elements
of the matrix in spiral order.
Function Signature:
from typing import List
def spiral_order(matrix: List[List[int]]) -> List[int]:
"""
Return all elements of the matrix in spiral order.
Parameters:
- matrix: A 2D matrix of integers.
Returns:
- List[int]: The elements in spiral order.
"""
# Your code here
Example:
# Input: matrix = [
# [1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]
# ]
# Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
# Explanation: The elements are visited in a spiral order.
# Input: matrix = [
# [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]
# Explanation: The elements are visited in a spiral order.
Note:
- The matrix may have a different number of rows and columns.
- The matrix may contain duplicates.
Instructions:
- Write the
spiral_order
function to solve the problem. - Implement your solution in Python.
- Provide clear comments in your code.
- Discuss the time and space complexity of your solution.
As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊