Skip to content

Instantly share code, notes, and snippets.

@jerrythomas
Created July 17, 2021 02:37
Show Gist options
  • Save jerrythomas/128d432a60874bbef37a758c0421f397 to your computer and use it in GitHub Desktop.
Save jerrythomas/128d432a60874bbef37a758c0421f397 to your computer and use it in GitHub Desktop.
"""
Given a matrix of size MxN find all groups of adjacent elements and print their size.
Empty spaces are marked with 0 and filled with 1. Adjacency is only horizontal or vertical.
"""
def scan(row, col, layout, items, used_pairs):
pair = (row, col)
if pair not in used_pairs and layout[row][col]:
items.append(pair)
used_pairs.add(pair)
if row < len(layout) - 1:
items, used_pairs = scan(row+1, col, layout, items, used_pairs)
if col < len(layout[row]) - 1:
items, used_pairs = scan(row, col+1, layout, items, used_pairs)
return items, used_pairs
def find_adjacent_items(rows, cols, matrix):
used_pairs = set()
adjacent_items = []
for row in range(rows):
for col in range(cols):
pair = (row, col)
if pair not in used_pairs and layout[row][col]:
result, used_pairs = scan(row, col, layout, [], used_pairs)
if result:
adjacent_items.append(result)
return adjacent_items
if __name__ == '__main__':
layout = [
[1, 0, 0, 1, 0],
[1, 0, 1, 0, 0],
[0, 0, 1, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 1, 1, 0]
]
result = find_adjacent_items(5, 5, layout)
for item in result:
print(len(item), item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment