from collections import defaultdict
def bfs(graph, start):
queue = []
visited = set()
queue.append(start) # Store root/starting node to visit
visited.add(start) # Visit starting node
while queue: # As long as there is any node
node = queue.pop(0) # take that node from queue
print(node, end=" ")
for neighbor in graph[node]: # explore contents (children) of that node
if neighbor not in visited: # check if that node is not visited
queue.append(neighbor) # store that node for visit
visited.add(neighbor) # visit that node
graph = defaultdict(list)
graph['A'] = ['B', 'C']
graph['B'] = ['A', 'D', 'E']
graph['C'] = ['A', 'F']
graph['D'] = ['B']
graph['E'] = ['B', 'F']
graph['F'] = ['C', 'E']
bfs(graph, 'A') # Output: A B C D E F
### Using networkx : For network analysis problem
import networkx as nx
def path_exists(G, node1, node2): # G is the graph where multiple nodes are connected with edges
"""
This function checks whether a path exists between two nodes (node1, node2) in graph G.
"""
visited_nodes = set()
queue = [node1]
for node in queue:
neighbors = list(G.neighbors(node))
if node2 in neighbors:
print('Path exists between nodes {0} and {1}'.format(node1, node2))
return True
break
else:
visited_nodes.add(node)
queue.extend([n for n in neighbors if n not in visited_nodes])
# Check to see if the final element of the queue has been reached
if node == queue[-1]:
print('Path does not exist between nodes {0} and {1}'.format(node1, node2))
# Place the appropriate return statement
return False