forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpiral Matrix III.js
38 lines (36 loc) · 1.11 KB
/
Spiral Matrix III.js
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
var spiralMatrixIII = function(rows, cols, rStart, cStart) {
let output = [];
let r = rStart, c = cStart;
let right = true, down = false, left = false, up = false;
let steps = 1, maxSteps = 2;
while (output.length !== (rows * cols)) {
if (r >= 0 && c >= 0 && r < rows && c < cols) output.push([r, c]);
if (right) {
if (steps + 1 > maxSteps) {
steps = 2, r++;
right = false, down = true;
} else c++, steps++;
}
else if (down) {
if (steps + 1 > maxSteps) {
steps = 2, c--;
down = false, left = true;
maxSteps++;
} else r++, steps++;
}
else if (left) {
if (steps + 1 > maxSteps) {
steps = 2, r--;
left = false, up = true;
} else c--, steps++;
}
else if (up) {
if (steps + 1 > maxSteps) {
steps = 2, c++;
up = false, right = true;
maxSteps++;
} else r--, steps++;
}
}
return output;
};