-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0980-unique-paths-iii.js
More file actions
80 lines (70 loc) · 1.88 KB
/
0980-unique-paths-iii.js
File metadata and controls
80 lines (70 loc) · 1.88 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Unique Paths III
* Time Complexity: O(rows * cols * 4^W)
* Space Complexity: O(rows * cols)
*/
var uniquePathsIII = function (grid) {
const gridLengthR = grid.length;
const gridLengthC = grid[0].length;
let allWalkableSquaresCount = 0;
let startPointRow;
let startPointCol;
for (let rowIndexer = 0; rowIndexer < gridLengthR; rowIndexer++) {
for (let colIndexer = 0; colIndexer < gridLengthC; colIndexer++) {
const currentCellContent = grid[rowIndexer][colIndexer];
if (
currentCellContent === 0 ||
currentCellContent === 1 ||
currentCellContent === 2
) {
allWalkableSquaresCount++;
}
if (currentCellContent === 1) {
startPointRow = rowIndexer;
startPointCol = colIndexer;
}
}
}
function pathFinder(currR, currC, stepsTaken) {
if (
currR < 0 ||
currR >= gridLengthR ||
currC < 0 ||
currC >= gridLengthC ||
grid[currR][currC] === -1
) {
return 0;
}
if (grid[currR][currC] === 2) {
return stepsTaken === allWalkableSquaresCount ? 1 : 0;
}
const currentCellVal = grid[currR][currC];
grid[currR][currC] = -1;
let totalPathsFromHere = 0;
const moveOptions = [
[0, 1],
[0, -1],
[1, 0],
[-1, 0],
];
for (
let idxDirection = 0;
idxDirection < moveOptions.length;
idxDirection++
) {
const deltaR = moveOptions[idxDirection][0];
const deltaC = moveOptions[idxDirection][1];
const nextVisitRow = currR + deltaR;
const nextVisitCol = currC + deltaC;
const recursiveResult = pathFinder(
nextVisitRow,
nextVisitCol,
stepsTaken + 1,
);
totalPathsFromHere += recursiveResult;
}
grid[currR][currC] = currentCellVal;
return totalPathsFromHere;
}
return pathFinder(startPointRow, startPointCol, 1);
};