
Sponsored
Sponsored
To simulate walking in a spiral, maintain a direction vector and a step count for each segment. Initially face east, and keep track of direction changes in the order of east, south, west, north. After two direction changes, increase the step count which determines how far to walk in the current direction before turning.
Time Complexity: O(rows * cols), since each cell is visited once,
Space Complexity: O(rows * cols), for the result storage.
1public class Solution {
2 public int[][] SpiralMatrixIII(int rows, int cols, int rStart, int cStart) {
3 int[][] result = new int[rows * cols][];
4 int[] dr = new int[] {0, 1, 0, -1};
5 int[] dc = new int[] {1, 0, -1, 0};
6 int x = rStart, y = cStart, steps = 0, dir = 0, k = 0;
7 result[k++] = new int[]{x, y};
8
9 while (k < rows * cols) {
10 if (dir == 0 || dir == 2) steps++;
11 for (int j = 0; j < steps; j++) {
12 x += dr[dir];
13 y += dc[dir];
14 if (x >= 0 && x < rows && y >= 0 && y < cols) {
15 result[k++] = new int[]{x, y};
16 }
17 }
18 dir = (dir + 1) % 4;
19 }
20 return result;
21 }
22}The C# solution uses a counter to track steps and an array to hold directions, effectively visiting each grid position in spiral order.