19
19
* @param {Number } rows Number of rows in the grid
20
20
* @param {Number } columns Number of columns in the grid
21
21
* @param {String | Number | Boolean } filler The value to fill cells
22
- * @returns {Object [] }
22
+ * @returns {Array [] [] }
23
23
*/
24
24
const generateMatrix = ( rows , columns , filler = 0 ) => {
25
25
const matrix = [ ]
26
- for ( let i = 0 ; i < rows ; i += 1 ) {
26
+ for ( let i = 0 ; i < rows ; i ++ ) {
27
27
const submatrix = [ ]
28
- for ( let k = 0 ; k < columns ; k += 1 ) {
28
+ for ( let k = 0 ; k < columns ; k ++ ) {
29
29
submatrix [ k ] = filler
30
30
}
31
31
matrix [ i ] = submatrix
@@ -35,11 +35,11 @@ const generateMatrix = (rows, columns, filler = 0) => {
35
35
36
36
/**
37
37
* @description Return number of unique paths
38
- * @param {Object [] } obstacles Obstacles grid
38
+ * @param {Array [] [] } obstacles Obstacles grid
39
39
* @returns {Number }
40
40
*/
41
41
const uniquePaths2 = ( obstacles ) => {
42
- if ( ! ( obstacles instanceof Object ) ) {
42
+ if ( ! Array . isArray ( obstacles ) ) {
43
43
throw new Error ( 'Input data must be type of Array' )
44
44
}
45
45
// Create grid for calculating number of unique ways
@@ -48,15 +48,15 @@ const uniquePaths2 = (obstacles) => {
48
48
const grid = generateMatrix ( rows , columns )
49
49
// Fill the outermost cell with 1 b/c it has
50
50
// the only way to reach neighbor
51
- for ( let i = 0 ; i < rows ; i += 1 ) {
51
+ for ( let i = 0 ; i < rows ; i ++ ) {
52
52
// If robot encounters an obstacle in these cells,
53
- // he cannot continue movind in that direction
53
+ // he cannot continue moving in that direction
54
54
if ( obstacles [ i ] [ 0 ] ) {
55
55
break
56
56
}
57
57
grid [ i ] [ 0 ] = 1
58
58
}
59
- for ( let j = 0 ; j < columns ; j += 1 ) {
59
+ for ( let j = 0 ; j < columns ; j ++ ) {
60
60
if ( obstacles [ 0 ] [ j ] ) {
61
61
break
62
62
}
@@ -65,13 +65,9 @@ const uniquePaths2 = (obstacles) => {
65
65
// Fill the rest of grid by dynamic programming
66
66
// using following reccurent formula:
67
67
// K[i][j] = K[i - 1][j] + K[i][j - 1]
68
- for ( let i = 1 ; i < rows ; i += 1 ) {
69
- for ( let j = 1 ; j < columns ; j += 1 ) {
70
- if ( obstacles [ i ] [ j ] ) {
71
- grid [ i ] [ j ] = 0
72
- } else {
73
- grid [ i ] [ j ] = grid [ i - 1 ] [ j ] + grid [ i ] [ j - 1 ]
74
- }
68
+ for ( let i = 1 ; i < rows ; i ++ ) {
69
+ for ( let j = 1 ; j < columns ; j ++ ) {
70
+ grid [ i ] [ j ] = obstacles [ i ] [ j ] ? 0 : grid [ i - 1 ] [ j ] + grid [ i ] [ j - 1 ]
75
71
}
76
72
}
77
73
return grid [ rows - 1 ] [ columns - 1 ]
0 commit comments