-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0885-spiral-matrix-iii.js
More file actions
47 lines (44 loc) · 1.23 KB
/
0885-spiral-matrix-iii.js
File metadata and controls
47 lines (44 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Spiral Matrix III
* Time Complexity: O(rows * cols)
* Space Complexity: O(rows * cols)
*/
var spiralMatrixIII = function (rowsInput, colsInput, startRow, startCol) {
const outputCoordinates = [];
const totalCells = rowsInput * colsInput;
let currentRow = startRow;
let currentCol = startCol;
let currentStepLength = 1;
let currentDirectionIndex = 0;
const movementVectors = [
[0, 1],
[1, 0],
[0, -1],
[-1, 0],
];
outputCoordinates.push([currentRow, currentCol]);
while (outputCoordinates.length < totalCells) {
for (let segmentIteration = 0; segmentIteration < 2; segmentIteration++) {
const [deltaRow, deltaCol] = movementVectors[currentDirectionIndex];
for (
let stepIteration = 0;
stepIteration < currentStepLength;
stepIteration++
) {
currentRow += deltaRow;
currentCol += deltaCol;
if (
currentRow >= 0 &&
currentRow < rowsInput &&
currentCol >= 0 &&
currentCol < colsInput
) {
outputCoordinates.push([currentRow, currentCol]);
}
}
currentDirectionIndex = (currentDirectionIndex + 1) % 4;
}
currentStepLength++;
}
return outputCoordinates;
};