Created
April 24, 2020 21:36
-
-
Save jasonrdsouza/c1b27ea908e0e654f5a06018b762c88f to your computer and use it in GitHub Desktop.
Snippet to count contiguous islands in a grid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
Node = namedtuple('Node', 'row col') | |
class IslandCounter: | |
def __init__(self, ocean_map): | |
self.map = ocean_map | |
self.max_row = len(ocean_map) | |
self.max_col = len(ocean_map[0]) | |
def is_land(self, node): | |
return self.map[node.row][node.col] == 1 | |
def valid_node(self, node): | |
valid_row = 0 <= node.row < self.max_row | |
valid_col = 0 <= node.col < self.max_col | |
return valid_row and valid_col | |
def neighbors(self, node): | |
all_neighbors = [ | |
Node(node.row + 1, node.col), | |
Node(node.row - 1, node.col), | |
Node(node.row, node.col + 1), | |
Node(node.row, node.col - 1) | |
] | |
return [neighbor for neighbor in all_neighbors if self.valid_node(neighbor)] | |
def explore_island(self, node, seen_land): | |
for neighbor in self.neighbors(node): | |
if self.is_land(neighbor) and neighbor not in seen_land: | |
seen_land.add(neighbor) | |
self.explore_island(neighbor, seen_land) | |
def count(self): | |
num_islands = 0 | |
seen_land = set() | |
for row in range(self.max_row): | |
for col in range(self.max_col): | |
node = Node(row, col) | |
if node in seen_land or not self.is_land(node): | |
pass | |
else: | |
num_islands += 1 | |
seen_land.add(node) | |
self.explore_island(node, seen_land) | |
return num_islands | |
# Testcases | |
ocean1 = [ | |
[0,0,0], | |
[0,1,0], | |
[0,0,0]] | |
ocean2 = [ | |
[0,1,0], | |
[0,0,0], | |
[0,1,0]] | |
ocean3 = [ | |
[1,1,0], | |
[1,1,0], | |
[0,0,0]] | |
ocean4 = [ | |
[1,0,1], | |
[0,0,0], | |
[1,0,1]] | |
ocean5 = [ | |
[0,0,1], | |
[0,1,1], | |
[0,0,1]] | |
assert(1 == IslandCounter(ocean1).count()) | |
assert(2 == IslandCounter(ocean2).count()) | |
assert(1 == IslandCounter(ocean3).count()) | |
assert(4 == IslandCounter(ocean4).count()) | |
assert(1 == IslandCounter(ocean5).count()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment