|
| 1 | +""" |
| 2 | +Breadth-first search (BFS) is an algorithm for searching tree or |
| 3 | +graph data structures. It produces a set of actions to be follwed to reach a |
| 4 | +target state from the start state. Starting at the initial state (often the |
| 5 | +root node for a tree) it explores all neighbor nodes at each level |
| 6 | +before moving to the next level. |
| 7 | +""" |
| 8 | + |
| 9 | +from collections import deque, namedtuple |
| 10 | + |
| 11 | + |
| 12 | +def breadth_first_search(graph, start, target): |
| 13 | + """ Performs a breadth-first search on a graph |
| 14 | +
|
| 15 | + Args: |
| 16 | + graph (list of list of int): Adjacency matrix representation of graph |
| 17 | + source (int): Index of source vertex to begin search from |
| 18 | +
|
| 19 | + Returns: |
| 20 | + tuple (path, distance): path traversed from start to target, total |
| 21 | + distance of path |
| 22 | + None,None if target not found |
| 23 | + """ |
| 24 | + vertex_info = {} |
| 25 | + VistitedVertex = namedtuple("VisitedVertex", "parent distance") |
| 26 | + vertex_info[start] = VistitedVertex(None, 0) |
| 27 | + |
| 28 | + search_queue = deque() |
| 29 | + visited = set() |
| 30 | + search_queue.append(start) |
| 31 | + |
| 32 | + while search_queue: |
| 33 | + u = search_queue.popleft() |
| 34 | + if u == target: |
| 35 | + return construct_path(u, vertex_info) |
| 36 | + for v in graph[u]: |
| 37 | + if v not in visited: |
| 38 | + if v not in search_queue: |
| 39 | + vertex_info[v] = VistitedVertex( |
| 40 | + u, vertex_info[u].distance + 1) |
| 41 | + search_queue.append(v) |
| 42 | + visited.add(u) |
| 43 | + return None, None |
| 44 | + |
| 45 | + |
| 46 | +def construct_path(vertex, vertex_info): |
| 47 | + path = [] |
| 48 | + distance = vertex_info[vertex].distance |
| 49 | + while True: |
| 50 | + path.append(vertex) |
| 51 | + if vertex_info[vertex].parent is not None: |
| 52 | + vertex = vertex_info[vertex].parent |
| 53 | + else: |
| 54 | + break |
| 55 | + return path[::-1], distance |
| 56 | + |
| 57 | + |
| 58 | +def main(): |
| 59 | + graph_adj_list = [ |
| 60 | + [1], |
| 61 | + [0, 4, 5], |
| 62 | + [3, 4, 5], |
| 63 | + [2, 6], |
| 64 | + [1, 2], |
| 65 | + [1, 2, 6], |
| 66 | + [3, 5], |
| 67 | + [] |
| 68 | + ] |
| 69 | + |
| 70 | + start = 0 |
| 71 | + target = 10 |
| 72 | + path, distance = breadth_first_search(graph_adj_list, start, target) |
| 73 | + print('Path from vertex {} to vertex {}: {}'.format(start, target, path)) |
| 74 | + print('Path distance: {}'.format(distance)) |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == '__main__': |
| 78 | + main() |
0 commit comments