Last active
April 14, 2020 09:09
-
-
Save surenkov/4740b32d3c8faf32fdfa4f293ba1a758 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 deque | |
field = [...] # NxM matrix | |
not_visited = {(x, y) for x in range(N) for y in range(M)} | |
def test_acceptance(x, y): | |
return field[x][y] == 1 and (x, y) in not_visited | |
def bfs(start_x, start_y): | |
queue = deque() | |
queue.append((start_x, start_y)) | |
connected_component = set() | |
while queue: | |
x, y = queue.popleft() | |
if test_acceptance(x, y): | |
connected_component.add((x, y)) | |
for i in (-1, 1): | |
next_x, next_y = x + i, y + i | |
if 0 <= next_x < N: | |
queue.append((next_x, y)) | |
if 0 <= next_y < M: | |
queue.append((x, next_y)) | |
not_visited.discard((x, y)) | |
return connected_component | |
all_components = [] | |
while not_visited: | |
x, y = not_visited.pop() | |
all_components.append(bfs(x, y)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment