|
| 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 | + * Reference for this problem: |
| 7 | + * - https://www.geeksforgeeks.org/rat-in-a-maze-backtracking-2/ |
| 8 | + * |
| 9 | + */ |
| 10 | + |
| 11 | +// Helper function to find if current cell is out of boundary |
| 12 | +const outOfBoundary = (grid, currentRow, currentColumn) => { |
| 13 | + if (currentRow < 0 || currentColumn < 0 || currentRow >= grid.length || currentColumn >= grid[0].length) { |
| 14 | + return true |
| 15 | + } else { |
| 16 | + return false |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +const printPath = (grid, currentRow, currentColumn, path) => { |
| 21 | + // If cell is out of boundary, we can't proceed |
| 22 | + if (outOfBoundary(grid, currentRow, currentColumn)) return false |
| 23 | + |
| 24 | + // If cell is blocked then you can't go ahead |
| 25 | + if (grid[currentRow][currentColumn] === 0) return false |
| 26 | + |
| 27 | + // If we reached target cell, then print path |
| 28 | + if (currentRow === targetRow && currentColumn === targetColumn) { |
| 29 | + console.log(path) |
| 30 | + return true |
| 31 | + } |
| 32 | + |
| 33 | + // R,L,D,U are directions `Right, Left, Down, Up` |
| 34 | + const directions = [ |
| 35 | + [1, 0, 'D'], |
| 36 | + [-1, 0, 'U'], |
| 37 | + [0, 1, 'R'], |
| 38 | + [0, -1, 'L'] |
| 39 | + ] |
| 40 | + |
| 41 | + for (let i = 0; i < directions.length; i++) { |
| 42 | + const nextRow = currentRow + directions[i][0] |
| 43 | + const nextColumn = currentColumn + directions[i][1] |
| 44 | + const updatedPath = path + directions[i][2] |
| 45 | + |
| 46 | + grid[currentRow][currentColumn] = 0 |
| 47 | + if (printPath(grid, nextRow, nextColumn, updatedPath)) return true |
| 48 | + grid[currentRow][currentColumn] = 1 |
| 49 | + } |
| 50 | + return false |
| 51 | +} |
| 52 | + |
| 53 | +// Driver Code |
| 54 | + |
| 55 | +const grid = [ |
| 56 | + [1, 1, 1, 1], |
| 57 | + [1, 0, 0, 1], |
| 58 | + [0, 0, 1, 1], |
| 59 | + [1, 1, 0, 1] |
| 60 | +] |
| 61 | + |
| 62 | +const targetRow = grid.length - 1 |
| 63 | +const targetColumn = grid[0].length - 1 |
| 64 | + |
| 65 | +// Variation 2 : print a possible path to reach from (0, 0) to (N-1, N-1) |
| 66 | +// If there is no path possible then it will print "Not Possible" |
| 67 | +!printPath(grid, 0, 0, '') && console.log('Not Possible') |
0 commit comments