Member-only story
30 Days of Algorithms: From Zero to Intermediate (27/30) —Island Count
We will hone our problem-solving skills by exploring the islands in a grid. In this part, we will count islands.
This technique can be used in Geographic Information Systems, Image Processing, Network Analysis, or Game Development.
It can help with creating procedurally generated game worlds, ensuring that landmasses, obstacles, or resources are distributed logically and artistically.
Grid
Let’s create a map of islands. We will mark islands with the number 1 and water with the number 0.
grid = [
[0, 1, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[1, 0, 0, 1, 1],
[1, 1, 0, 0, 0],
]
Auxiliary variables
First, we check if the grid exists; if not, we return 0
. We then create a visited
list to match the grid’s size, initializing it with all False
values.
Finally, we create a count variable for counting islands, setting its default value to 0
.
def count_islands(grid):
if not grid or not grid[0]:
return 0
num_rows = len(grid)
num_cols = len(grid[0])
visited = [[False for _ in range(num_cols)] for _ in range(num_rows)]
count = 0