|
1 | 1 | # 200. Number of Islands |
2 | 2 |
|
3 | | -## Traditional DFS Recursive |
| 3 | +## Traditional DFS Recursive Solution |
| 4 | +- Runtime: O(N) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of elements in grid |
| 7 | + |
4 | 8 | Using a visited set and recursion to achieve a solution. |
5 | 9 | ``` |
6 | 10 | class Solution: |
@@ -36,7 +40,12 @@ class Solution: |
36 | 40 | return traverse_helper(grid) |
37 | 41 | ``` |
38 | 42 |
|
39 | | -## Traditional BFS Iterative |
| 43 | +## Traditional BFS Iterative Solution |
| 44 | +- Runtime: O(N) |
| 45 | +- Space: O(N) |
| 46 | +- N = Number of elements in grid |
| 47 | + |
| 48 | +Similar concept to the previous DFS recursion but now using BFS and a stack. |
40 | 49 | ``` |
41 | 50 | class Solution: |
42 | 51 | def numIslands(self, grid: List[List[str]]) -> int: |
@@ -75,3 +84,46 @@ class Solution: |
75 | 84 | |
76 | 85 | return traverse_helper(grid) |
77 | 86 | ``` |
| 87 | + |
| 88 | +## O(1) Space BFS Iterative Solution |
| 89 | +- Runtime: O(N) |
| 90 | +- Space: O(1) |
| 91 | +- N = Number of elements in grid |
| 92 | + |
| 93 | +We can achieve O(1) space by reusing the given the grid. You should ask the interviewer if you are allowed to modify the original grid. We can then use another number such as "-1" to represented an already visited island, therefore, no longer needing a visited set during our BFS or DFS. |
| 94 | +``` |
| 95 | +class Solution: |
| 96 | + def numIslands(self, grid: List[List[str]]) -> int: |
| 97 | + def traverse_helper(grid): |
| 98 | + n_islands = 0 |
| 99 | + for y_index, y in enumerate(grid): |
| 100 | + for x_index, x in enumerate(y): |
| 101 | + if x == '1': |
| 102 | + n_islands += 1 |
| 103 | + traverse_islands_bfs_iterative(x_index, y_index, grid) |
| 104 | + return n_islands |
| 105 | + |
| 106 | + def traverse_islands_bfs_iterative(x, y, grid): |
| 107 | + stack = list() |
| 108 | + stack.append((x,y)) |
| 109 | + while len(stack) > 0: |
| 110 | + x_index, y_index = stack.pop() |
| 111 | + grid[y_index][x_index] = '-1' |
| 112 | + for x_neighbor, y_neighbor in get_neighbors_gen(x_index, y_index, grid): |
| 113 | + if within_bounds(x_neighbor, y_neighbor, grid) \ |
| 114 | + and grid[y_neighbor][x_neighbor] == '1': |
| 115 | + stack.append((x_neighbor, y_neighbor)) |
| 116 | + |
| 117 | + def get_neighbors_gen(x, y, grid): |
| 118 | + yield x, y-1 # top |
| 119 | + yield x, y+1 # bottom |
| 120 | + yield x-1, y # left |
| 121 | + yield x+1, y # right |
| 122 | + |
| 123 | + def within_bounds(x, y, grid): |
| 124 | + if y >= 0 and y < len(grid) and x >= 0 and x < len(grid[0]): |
| 125 | + return True |
| 126 | + return False |
| 127 | + |
| 128 | + return traverse_helper(grid) |
| 129 | +``` |
0 commit comments