|
| 1 | +/* |
| 2 | + * Problem Statement: |
| 3 | + * - Given a NxN grid, find whether rat in cell (0,0) can reach target(N-1,N-1); |
| 4 | + * - In grid "0" represent blocked cell and "1" represent empty cell |
| 5 | + * |
| 6 | + */ |
| 7 | + |
| 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 |
| 11 | +} |
| 12 | + |
| 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 |
| 37 | +} |
| 38 | + |
| 39 | +// Driver Code |
| 40 | + |
| 41 | +const grid = [ |
| 42 | + [1, 1, 1, 1], |
| 43 | + [1, 0, 0, 1], |
| 44 | + [0, 1, 0, 1], |
| 45 | + [1, 1, 1, 1] |
| 46 | +] |
| 47 | + |
| 48 | +const targetRow = grid.length - 1 |
| 49 | +const targetColumn = grid[0].length - 1 |
| 50 | + |
| 51 | +if (isPossible(grid, 0, 0)) { |
| 52 | + console.log('Possible') |
| 53 | +} else { |
| 54 | + console.log('Not Possible') |
| 55 | +} |
0 commit comments