#885
Spiral Matrix III
MediumArrayMatrixSimulationSimulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a systematic approach to determine the next position based on the current direction and the number of steps taken. It efficiently tracks the boundaries and adjusts the direction accordingly without unnecessary checks.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty list for coordinates and set the current position and direction.
- 2Step 2: Use a loop that continues until all cells are visited, adjusting the direction and steps as needed.
- 3Step 3: Append valid coordinates to the result list while moving in the current direction.
solution.py16 lines
1def spiralMatrixIII(rows, cols, rStart, cStart):
2 result = []
3 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
4 x, y = rStart, cStart
5 steps = 1
6 while len(result) < rows * cols:
7 for direction in directions:
8 for _ in range(steps):
9 if 0 <= x < rows and 0 <= y < cols:
10 result.append([x, y])
11 x += direction[0]
12 y += direction[1]
13 if direction in [(0, 1), (0, -1)]:
14 steps += 1
15 return result
16ℹ
Complexity note: The optimal solution efficiently traverses through the grid, visiting each cell exactly once, leading to linear time complexity relative to the number of cells.
- 1The spiral movement can be visualized as a series of layers expanding outward.
- 2Boundary conditions are crucial to ensure valid cell visits.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.