forked from citxx/sis-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs-path-restoration.py
44 lines (31 loc) · 1.09 KB
/
bfs-path-restoration.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/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[start] = True
previous = [None] * len(graph) # previous[v] - вершина, предшествующая
# вершине v в кратчайшем пути от start.
while len(to_visit) > 0:
u = to_visit.popleft()
for v in graph[u]:
if not considered[v]:
previous[v] = u
to_visit.append(v)
considered[v] = True
return previous
def restore_path(previous, finish):
path = []
v = finish
while v is not None:
path.append(v)
v = previous[v]
path.reverse()
return path
if __name__ == '__main__':
previous = bfs([[1], [2], [1], [0]], 0)
print(restore_path(previous, 2))