/54. Spiral Matrix

54. Spiral Matrix

Medium
Arrays56.3% acceptance

Given a 2D integer array grid of dimensions m x n, return a list containing all elements of grid traversed in spiral order, starting from the top-left element and proceeding clockwise.

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 spiral.

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: [[1,2],[3,4]]

Expected: [1,2,4,3]

Case 2

Input: [[7]]

Expected: [7]

Case 3

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

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

Case 4

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

Expected: [1,2,3,4]