Recursive Backtracking Depth First Search Algorithm Starting from top left of a matrix, count the number of paths that can reach the bottom right of a matrix. 1 represents a block (inaccessible) 0 represents a valid space (accessible) 0 0 0 0 1 1 0 0 0 0 0
(grid: list[list[int]], row: int, col: int, visit: set)
| 21 | |
| 22 | |
| 23 | def depth_first_search(grid: list[list[int]], row: int, col: int, visit: set) -> int: |
| 24 | """ |
| 25 | Recursive Backtracking Depth First Search Algorithm |
| 26 | |
| 27 | Starting from top left of a matrix, count the number of |
| 28 | paths that can reach the bottom right of a matrix. |
| 29 | 1 represents a block (inaccessible) |
| 30 | 0 represents a valid space (accessible) |
| 31 | |
| 32 | 0 0 0 0 |
| 33 | 1 1 0 0 |
| 34 | 0 0 0 1 |
| 35 | 0 1 0 0 |
| 36 | >>> grid = [[0, 0, 0, 0], [1, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]] |
| 37 | >>> depth_first_search(grid, 0, 0, set()) |
| 38 | 2 |
| 39 | |
| 40 | 0 0 0 0 0 |
| 41 | 0 1 1 1 0 |
| 42 | 0 1 1 1 0 |
| 43 | 0 0 0 0 0 |
| 44 | >>> grid = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]] |
| 45 | >>> depth_first_search(grid, 0, 0, set()) |
| 46 | 2 |
| 47 | """ |
| 48 | row_length, col_length = len(grid), len(grid[0]) |
| 49 | if ( |
| 50 | min(row, col) < 0 |
| 51 | or row == row_length |
| 52 | or col == col_length |
| 53 | or (row, col) in visit |
| 54 | or grid[row][col] == 1 |
| 55 | ): |
| 56 | return 0 |
| 57 | if row == row_length - 1 and col == col_length - 1: |
| 58 | return 1 |
| 59 | |
| 60 | visit.add((row, col)) |
| 61 | |
| 62 | count = 0 |
| 63 | count += depth_first_search(grid, row + 1, col, visit) |
| 64 | count += depth_first_search(grid, row - 1, col, visit) |
| 65 | count += depth_first_search(grid, row, col + 1, visit) |
| 66 | count += depth_first_search(grid, row, col - 1, visit) |
| 67 | |
| 68 | visit.remove((row, col)) |
| 69 | return count |
| 70 | |
| 71 | |
| 72 | if __name__ == "__main__": |