Skip to content

Commit 69a49dc

Browse files
author
Joseph Luce
authored
Update number_of_islands.md
1 parent 93369fe commit 69a49dc

File tree

1 file changed

+54
-2
lines changed

1 file changed

+54
-2
lines changed

leetcode/medium/number_of_islands.md

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
# 200. Number of Islands
22

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+
48
Using a visited set and recursion to achieve a solution.
59
```
610
class Solution:
@@ -36,7 +40,12 @@ class Solution:
3640
return traverse_helper(grid)
3741
```
3842

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.
4049
```
4150
class Solution:
4251
def numIslands(self, grid: List[List[str]]) -> int:
@@ -75,3 +84,46 @@ class Solution:
7584
7685
return traverse_helper(grid)
7786
```
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

Comments
 (0)