885. Spiral Matrix III
Array, Matrix, Simulation, AMateList ·Problem Statement
link: LeetCode.cn LeetCode You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid’s boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.
Return an array of coordinates representing the positions of the grid in the order you visited them.
Example:
Input: rows = 1, cols = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]
Input: rows = 5, cols = 6, rStart = 1, cStart = 4
Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
Constraints: 1 <= rows, cols <= 100 0 <= rStart < rows 0 <= cStart < cols
Solution Approach
The solution simulates walking in a clockwise spiral pattern, incrementally expanding the steps in each direction, while collecting valid grid positions until all cells are covered.
Algorithm
- Spiral Movement: The algorithm simulates the movement in a spiral pattern (right, down, left, and up), with each direction’s step size increasing as needed to cover the entire grid.
- Boundary Check: During each move, the algorithm checks whether the new position is within the grid boundaries and only adds valid positions to the result list.
- Incremental Expansion: The step size for each direction is incremented after every two turns (right/down and left/up) to ensure the spiral expands outward correctly, eventually covering all cells in the grid.
Complexity
time complexity: O(rows * cols) space complexity: O(rows * cols)
Implement
class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
res =[(rStart, cStart)]
if rows * cols == 1:
return res
for k in range(1, 2*(rows + cols), 2):
for dx, dy, step in [(0, 1, k),(1, 0, k),(0, -1, k + 1),(-1, 0, k + 1)]:
for i in range(step):
rStart, cStart = rStart + dx, cStart + dy
if 0 <= rStart < rows and 0 <= cStart < cols:
res.append((rStart, cStart))
if len(res) == rows * cols:
return res