Loading…
Loading…
Given an R x C matrix, return every element in spiral order — starting top-left, moving right, then down, then left, then up, shrinking inward each lap.
Input:
11 2 3
24 5 6
37 8 9Output: 1 2 3 6 9 8 7 4 5
Track four shrinking boundaries — top, bottom, left, right. Each lap: walk the top row left-to-right (then push top down), the right column top-to-bottom (then pull right in), the bottom row right-to-left if a bottom row still remains (then pull bottom up), and the left column bottom-to-top if a left column still remains (then push left in). The two "if" guards matter — without them, a single remaining row or column gets walked twice once the boundaries cross.
1def spiral_matrix(grid):
2 top, bottom = 0, len(grid) - 1
3 left, right = 0, len(grid[0]) - 1
4 result = []
5 while top <= bottom and left <= right:
6 for col in range(left, right + 1):
7 result.append(grid[top][col])
8 top += 1
9 for row in range(top, bottom + 1):
10 result.append(grid[row][right])
11 right -= 1
12 if top <= bottom:
13 for col in range(right, left - 1, -1):
14 result.append(grid[bottom][col])
15 bottom -= 1
16 if left <= right:
17 for row in range(bottom, top - 1, -1):
18 result.append(grid[row][left])
19 left += 1
20 return resultLine 1: R C
Next R lines: C space-separated integers
Print the spiral order, space-separated.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.