Question: Make a python implementation in 'BFS' below to find the path, if no path, should return an empty list. Will rate. For example, BFS(G, 0,
Make a python implementation in 'BFS' below to find the path, if no path, should return an empty list. Will rate. For example, BFS(G, 0, 9) should return [0, 1, 4, 7, 2, 5, 8, 9]
from collections import deque class Graph: def __init__(self, n): self.adj = {} for i in range(n): self.adj[i] = [] def are_connected(self, node1, node2): return node2 in self.adj[node1] def adjacent_nodes(self, node): return self.adj[node] def add_node(self): self.adj[len(self.adj)] = [] def add_edge(self, node1, node2): if node1 not in self.adj[node2]: self.adj[node1].append(node2) self.adj[node2].append(node1) def number_of_nodes(): return len() def BFS(G, start, end): newList = [] Q = deque([node1]) marked = {node1 : True} for node in G.adj: if node != node1: marked[node] = False while len(Q) != 0: curr_node = Q.popleft() for node in G.adj[curr_node]: if node == node2: return True if not marked[node]: Q.append(node) marked[node] = True return False G = Graph(10) G.add_edge(0, 1) G.add_edge(0, 4) G.add_edge(0, 7) G.add_edge(1, 2) G.add_edge(2, 3) G.add_edge(4, 5) G.add_edge(5, 6) G.add_edge(7, 8) G.add_edge(8, 9)
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
