|
| 1 | +def bfs(g,N): |
| 2 | + ''' |
| 3 | + :param g: given adjacency list of graph |
| 4 | + :param N: number of nodes in N. |
| 5 | + ''' |
| 6 | + # code here |
| 7 | + # level determines the cost/steps to reach specific node from start node |
| 8 | + # level where a vertex is located from the initial considered vertex |
| 9 | + level = {0:0} |
| 10 | + # parent stores the path to vertices, to determine the edges |
| 11 | + # we can also caculate the shortest path taken by accessing the parent |
| 12 | + # of specific vertex(value of that vertex(key)), again checking |
| 13 | + # value/parent of the previous parent vertex. |
| 14 | + # assume: v <- c |
| 15 | + # c <- x |
| 16 | + # x <- s |
| 17 | + # s <- None |
| 18 | + # until we get None/specific assumed parent vertex |
| 19 | + # refer MIT lecture video BFS 6.006 |
| 20 | + parent = {0:None} |
| 21 | + # first level 0 is already set, the intial/start vertex 0 |
| 22 | + # so now moving towards i = 1 and exploring other levels accessible |
| 23 | + # to that initial/start vertex |
| 24 | + i = 1 |
| 25 | + # a list storing the vertices we have to currently explore |
| 26 | + frontier = [0] |
| 27 | + print(frontier[0], end=' ') |
| 28 | + while frontier: |
| 29 | + # next_ stores the edge nodes that are to be explored for each vertex |
| 30 | + next_ = [] |
| 31 | + # Below for loop iterates over vertices present in the Adjacency List |
| 32 | + for u in frontier: |
| 33 | + # Below for loop iterates over the edges/neighbouring vertices |
| 34 | + for v in g[u]: |
| 35 | + # avoids duplicacy of vertices, thus, avoiding duplicate |
| 36 | + # edges and cycling of graph |
| 37 | + if v not in level: |
| 38 | + level[v] = i |
| 39 | + parent[v] = u |
| 40 | + next_.append(v) |
| 41 | + print(v, end=' ') |
| 42 | + frontier = next_ |
| 43 | + i += 1 |
0 commit comments