885. Spiral Matrix III
MediumView on LeetCode
Time: O(r · c)
Space: O(r · c)
Advertisement
Intuition
Simulate spiral traversal: move right 1, down 1, left 2, up 2, right 3... Pattern increases every 2 turns. Add only valid grid cells.
Algorithm
- 1Directions: E,S,W,N. Step sizes: 1,1,2,2,3,3,4,4,...
- 2Move in current direction, add valid cells. Change direction, repeat.
Common Pitfalls
- •Continue even when outside grid. Only add cells that are within bounds.
885.cs
C#
// Approach: Simulate spiral walk; increment step size every 2 turns; collect only cells within grid bounds.
// Time: O(r · c) Space: O(r · c)
public class Solution
{
public int[][] SpiralMatrixIII(int rows, int cols, int rStart, int cStart)
{
int[] dx = { 1, 0, -1, 0 };
int[] dy = { 0, 1, 0, -1 };
var ans = new List<int[]> { new int[] { rStart, cStart } };
for (int i = 0; ans.Count < rows * cols; i++)
{
for (int step = 0; step < i / 2 + 1; step++)
{
rStart += dy[i % 4];
cStart += dx[i % 4];
if (rStart >= 0 && rStart < rows && cStart >= 0 && cStart < cols)
ans.Add(new int[] { rStart, cStart });
}
}
return ans.ToArray();
}
}Advertisement
Was this solution helpful?