|
6 | 6 | */
|
7 | 7 |
|
8 | 8 | const outOfBoundary = (grid, currentRow, currentColumn) => {
|
9 |
| - if (currentRow < 0 || currentColumn < 0 || currentRow >= grid.length || currentColumn >= grid[0].length) return true |
10 |
| - else return false |
| 9 | + if (currentRow < 0 || currentColumn < 0 || currentRow >= grid.length || currentColumn >= grid[0].length) return true |
| 10 | + else return false |
11 | 11 | }
|
12 | 12 |
|
13 | 13 | const isPossible = (grid, currentRow, currentColumn) => {
|
14 |
| - if (outOfBoundary(grid, currentRow, currentColumn)) return false |
15 |
| - |
16 |
| - console.log(currentRow, currentColumn) |
17 |
| - if (grid[currentRow][currentColumn] === 0) return false |
18 |
| - |
19 |
| - if (currentRow === targetRow && currentColumn === targetColumn) { |
20 |
| - return true |
21 |
| - } |
22 |
| - |
23 |
| - const directions = [ |
24 |
| - [1, 0], |
25 |
| - [0, 1], |
26 |
| - [-1, 0], |
27 |
| - [0, -1] |
28 |
| - ] |
29 |
| - |
30 |
| - for (let i = 0; i < directions.length; i++) { |
31 |
| - const nextRow = currentRow + directions[i][0]; const nextColumn = currentColumn + directions[i][1] |
32 |
| - grid[currentRow][currentColumn] = 0 |
33 |
| - if (isPossible(grid, nextRow, nextColumn)) return true |
34 |
| - grid[currentRow][currentColumn] = 1 |
35 |
| - } |
36 |
| - return false |
| 14 | + if (outOfBoundary(grid, currentRow, currentColumn)) return false |
| 15 | + |
| 16 | + if (grid[currentRow][currentColumn] === 0) return false |
| 17 | + |
| 18 | + if (currentRow === targetRow && currentColumn === targetColumn) { |
| 19 | + return true |
| 20 | + } |
| 21 | + |
| 22 | + const directions = [ |
| 23 | + [1, 0], |
| 24 | + [0, 1], |
| 25 | + [-1, 0], |
| 26 | + [0, -1] |
| 27 | + ] |
| 28 | + |
| 29 | + for (let i = 0; i < directions.length; i++) { |
| 30 | + const nextRow = currentRow + directions[i][0]; const nextColumn = currentColumn + directions[i][1] |
| 31 | + grid[currentRow][currentColumn] = 0 |
| 32 | + if (isPossible(grid, nextRow, nextColumn)) return true |
| 33 | + grid[currentRow][currentColumn] = 1 |
| 34 | + } |
| 35 | + return false |
37 | 36 | }
|
38 | 37 |
|
39 | 38 | // Driver Code
|
40 | 39 |
|
41 | 40 | const grid = [
|
42 |
| - [1, 1, 1, 1], |
43 |
| - [1, 0, 0, 1], |
44 |
| - [0, 1, 0, 1], |
45 |
| - [1, 1, 1, 1] |
| 41 | + [1, 1, 1, 1], |
| 42 | + [1, 0, 0, 1], |
| 43 | + [0, 0, 1, 0], |
| 44 | + [1, 1, 0, 1] |
46 | 45 | ]
|
47 | 46 |
|
48 | 47 | const targetRow = grid.length - 1
|
49 | 48 | const targetColumn = grid[0].length - 1
|
50 | 49 |
|
51 | 50 | if (isPossible(grid, 0, 0)) {
|
52 |
| - console.log('Possible') |
| 51 | + console.log('Possible') |
53 | 52 | } else {
|
54 |
| - console.log('Not Possible') |
| 53 | + console.log('Not Possible') |
55 | 54 | }
|
0 commit comments