/54. Spiral Matrix

54. Spiral Matrix

Medium
Arrays56.3% acceptance

Given a two-dimensional integer array grid of dimensions m x n, return a list of all elements in grid traversed in spiral order, starting from the top-left element and moving right, then down, then left, then up, and repeating this process until all elements are visited.

Example 1

Input: [[10, 20, 30], [40, 50, 60], [70, 80, 90]]

Output: [10, 20, 30, 60, 90, 80, 70, 40, 50]

Explanation: Spiral order: top row, right column, bottom row reversed, left column reversed, center.

Example 2

Input: [[5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

Output: [5, 6, 7, 8, 12, 16, 15, 14, 13, 9, 10, 11]

Explanation: Spiral order: top row, right column, bottom row reversed, left column reversed, inner row.

Constraints

  • 1 <= len(grid) <= 10
  • 1 <= len(grid[0]) <= 10
  • -100 <= grid[i][j] <= 100 for all valid i, j
Python (current runtime)

Case 1

Input: [[2, 4], [6, 8]]

Expected: [2, 4, 8, 6]

Case 2

Input: [[1]]

Expected: [1]

Case 3

Input: [[3, 5, 7]]

Expected: [3, 5, 7]

Case 4

Input: [[9], [8], [7]]

Expected: [9, 8, 7]

Case 5

Input: [[1, 2], [3, 4], [5, 6]]

Expected: [1, 2, 4, 6, 5, 3]