Skip to content

Instantly share code, notes, and snippets.

@CunningDJ
Last active June 17, 2024 16:35
Show Gist options
  • Save CunningDJ/21c4e799204a33aab27c42e2d2f9b275 to your computer and use it in GitHub Desktop.
Save CunningDJ/21c4e799204a33aab27c42e2d2f9b275 to your computer and use it in GitHub Desktop.
Leetcode: Number of Islands, with algorithm for grouping the islands by ID
'''
This solves the Number of Islands problem in Leetcode, but also creates unique
incrementing integer IDs for each island, and tracks all the coordinates that
make up each.
To solve the problem, you just return current_island_id + 1
To see the grouped islands by ID, return islands
Problem: https://leetcode.com/problems/number-of-islands
'''
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
LAND = '1'
WATER = '0'
rows = len(grid)
cols = len(grid[0])
current_island_id = -1
visited = set()
islands = {}
st = []
for ri in range(rows):
for ci in range(cols):
if grid[ri][ci] == LAND and not (ri,ci) in visited:
current_island_id += 1
islands[current_island_id] = set()
st.append((ri,ci))
else:
visited.add((ri,ci))
while st:
r, c = st.pop()
if (r,c) in visited:
continue
visited.add((r,c))
if grid[r][c] == WATER:
continue
islands[current_island_id].add((r,c))
if r > 0:
st.append((r-1,c))
if r < rows-1:
st.append((r+1,c))
if c > 0:
st.append((r,c-1))
if c < cols-1:
st.append((r,c+1))
# To give the desired answer:
# return current_island_id + 1
# To see the islands that are now grouped:
return islands
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment