|
| 1 | +""" |
| 2 | +Given a grid, where you start from the top left position [0, 0], |
| 3 | +you want to find how many paths you can take to get to the bottom right position. |
| 4 | +
|
| 5 | +start here -> 0 0 0 0 |
| 6 | + 1 1 0 0 |
| 7 | + 0 0 0 1 |
| 8 | + 0 1 0 0 <- finish here |
| 9 | +how many 'distinct' paths can you take to get to the finish? |
| 10 | +Using a recursive depth-first search algorithm below, you are able to |
| 11 | +find the number of distinct unique paths (count). |
| 12 | +
|
| 13 | +'*' will demonstrate a path |
| 14 | +In the example above, there are two distinct paths: |
| 15 | +1. 2. |
| 16 | + * * * 0 * * * * |
| 17 | + 1 1 * 0 1 1 * * |
| 18 | + 0 0 * 1 0 0 * 1 |
| 19 | + 0 1 * * 0 1 * * |
| 20 | +""" |
| 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__": |
| 73 | + import doctest |
| 74 | + |
| 75 | + doctest.testmod() |
0 commit comments