
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.
1var spiralMatrixIII = function(rows, cols, rStart, cStart) {
2 const result = [];
3 let x = rStart, y = cStart, steps = 1, dir = 0;
4 const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
5 result.push([x, y]);
6
7 while (result.length < rows * cols) {
8 if (dir % 2 === 0) {
9 for (let i = 0; i < steps; i++) {
10 x += directions[dir][0];
11 y += directions[dir][1];
12 if (x >= 0 && x < rows && y >= 0 && y < cols) {
13 result.push([x, y]);
14 }
15 }
16 } else {
17 for (let i = 0; i < steps; i++) {
18 x += directions[dir][0];
19 y += directions[dir][1];
20 if (x >= 0 && x < rows && y >= 0 && y < cols) {
21 result.push([x, y]);
22 }
23 }
24 steps++;
25 }
26 dir = (dir + 1) % 4;
27 }
28 return result;
29};This JavaScript solution iterates over directional pairs with correct step management to ensure all positions are visited in spiral order.