Spiral Order (From Center)

Given a positive and odd integer n, return an n x n grid filled with integers from 0 to n^2 - 1 in spiral order.

Rules:

  • Start at the center cell and place 0.
  • Move down first, then continue turning clockwise.
  • Keep placing the next number whenever you step into a valid cell.

Illustration (n = 5):

Spiral Order From Center (n=5)

Example:

  • Input: n = 3
  • Output: [[4,5,6],[3,0,7],[2,1,8]]
456
307
218
  • Explanation:
    • Start at center (1,1): 0
    • Move Down: (2,1) -> 1
    • Move Left: (2,0) -> 2
    • Move Up: (1,0) -> 3, (0,0) -> 4
    • Move Right: (0,1) -> 5, (0,2) -> 6
    • Move Down: (1,2) -> 7, (2,2) -> 8
1def spiralOrderCenter(n: int) -> List[List[int]]:
2 grid = [[0] * n for _ in range(n)]
3 r, c = n // 2, n // 2
4 grid[r][c] = 0
5 curr = 1
6
7 # Directions: Down, Left, Up, Right
8 directions = [(1, 0), (0, -1), (-1, 0), (0, 1)]
9 dir_idx = 0
10 steps = 1
11
12 while curr < n * n:
13 for _ in range(2): # Change step size every 2 directions
14 dr, dc = directions[dir_idx]
15 for _ in range(steps):
16 if curr >= n * n:
17 break
18 r += dr
19 c += dc
20 if 0 <= r < n and 0 <= c < n:
21 grid[r][c] = curr
22 curr += 1
23 dir_idx = (dir_idx + 1) % 4
24 steps += 1
25
26 return grid
-
-
-
-
0
-
-
-
-
r=1
c=1
curr=1
steps=1
Step 1 / 6
Step 1:
Start at the center (1,1) with value 0.
Focus: select @ [4]
r=1c=1curr=1steps=1