forked from citxx/sis-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.py
30 lines (21 loc) · 878 Bytes
/
bfs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Contributors:
# Artem Tabolin <[email protected]>
"""Поиск в ширину на списках смежности, выделяющий компоненту связности"""
from collections import deque
def bfs(graph, start):
to_visit = deque([start])
considered = [False] * len(graph) # considered[v] - добавлялась ли вершина
# v в очередь.
considered[start] = True
while len(to_visit) > 0:
u = to_visit.popleft()
for v in graph[u]:
if not considered[v]:
to_visit.append(v)
considered[v] = True
return considered
if __name__ == '__main__':
visited = bfs([[1], [2], [1], [0]], 0)
print([v for v in range(len(visited)) if visited[v]])