Skip to content

Commit e2e87c0

Browse files
authored
Create 980-unique-paths-iii.js
1 parent 99755b2 commit e2e87c0

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

980-unique-paths-iii.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
const uniquePathsIII = function(grid) {
6+
const obj = {
7+
eNum: 1,
8+
res: 0,
9+
rows: grid.length,
10+
dirs: [[-1, 0], [1, 0], [0, -1], [0, 1]],
11+
sr: 0,
12+
sc: 0,
13+
er: 0,
14+
ec: 0
15+
}
16+
if (obj.rows === 0) return 0
17+
obj.cols = grid[0].length
18+
for (let i = 0; i < obj.rows; i++) {
19+
for (let j = 0; j < obj.cols; j++) {
20+
if (grid[i][j] === 0) obj.eNum++
21+
else if (grid[i][j] === 1) (obj.sr = i), (obj.sc = j)
22+
else if (grid[i][j] === 2) (obj.er = i), (obj.ec = j)
23+
}
24+
}
25+
bt(grid, obj.sr, obj.sc, obj)
26+
return obj.res
27+
}
28+
29+
function bt(grid, x, y, obj) {
30+
if (x < 0 || x >= obj.rows || y < 0 || y >= obj.cols || grid[x][y] < 0) return
31+
if (x === obj.er && y === obj.ec) {
32+
if (obj.eNum === 0) obj.res++
33+
return
34+
}
35+
grid[x][y] = -2
36+
obj.eNum--
37+
for (let dir of obj.dirs) {
38+
bt(grid, x + dir[0], y + dir[1], obj)
39+
}
40+
obj.eNum++
41+
grid[x][y] = 0
42+
}

0 commit comments

Comments
 (0)