forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniquePaths2.js
More file actions
Latest commit
76 lines (73 loc) · 2.26 KB
/
Copy pathUniquePaths2.js
File metadata and controls
76 lines (73 loc) · 2.26 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
/*
* Unique Paths 2
*
* There is a robot on an `m x n` grid.
* The robot is initially located at the top-left corner
* The robot tries to move to the bottom-right corner.
* The robot can only move either down or right at any point in time.
*
* Given grid with obstacles
* An obstacle and space are marked as 1 or 0 respectively in grid.
* A path that the robot takes cannot include any square that is an obstacle.
* Return the number of possible unique paths that the robot can take to reach the bottom-right corner.
*
* More info: https://leetcode.com/problems/unique-paths-ii/
*/
/**
* @description Return 'rows x columns' grid with cells filled by 'filler'
* @param {Number} rows Number of rows in the grid
* @param {Number} columns Number of columns in the grid
* @param {String | Number | Boolean} filler The value to fill cells
* @returns {Array [][]}
*/
constgenerateMatrix=(rows,columns,filler=0)=>{
constmatrix=[]
for(leti=0;i<rows;i++){
constsubmatrix=[]
for(letk=0;k<columns;k++){
submatrix[k]=filler
}
matrix[i]=submatrix
}
returnmatrix
}
/**
* @description Return number of unique paths
* @param {Array [][]} obstacles Obstacles grid
* @returns {Number}
*/
constuniquePaths2=(obstacles)=>{
if(!Array.isArray(obstacles)){
thrownewError('Input data must be type of Array')
}
// Create grid for calculating number of unique ways
constrows=obstacles.length
constcolumns=obstacles[0].length
constgrid=generateMatrix(rows,columns)
// Fill the outermost cell with 1 b/c it has
// the only way to reach neighbor
for(leti=0;i<rows;i++){
// If robot encounters an obstacle in these cells,
// he cannot continue moving in that direction
if(obstacles[i][0]){
break
}
grid[i][0]=1
}
for(letj=0;j<columns;j++){
if(obstacles[0][j]){
break
}
grid[0][j]=1
}
// Fill the rest of grid by dynamic programming
// using following recurrent formula:
// K[i][j] = K[i - 1][j] + K[i][j - 1]
for(leti=1;i<rows;i++){
for(letj=1;j<columns;j++){
grid[i][j]=obstacles[i][j] ? 0 : grid[i-1][j]+grid[i][j-1]
}
}
returngrid[rows-1][columns-1]
}
export{uniquePaths2}