Skip to content

Instantly share code, notes, and snippets.

@MLWhiz
Created January 20, 2019 18:05
Show Gist options
  • Save MLWhiz/a9c4ee223295382c1284eef68f51d739 to your computer and use it in GitHub Desktop.
Save MLWhiz/a9c4ee223295382c1284eef68f51d739 to your computer and use it in GitHub Desktop.
#We add another countries in the loop
graph = Graph(g)
graph.add_edge(("Mumbai", "Delhi"),400)
graph.add_edge(("Delhi", "Kolkata"),500)
graph.add_edge(("Kolkata", "Bangalore"),600)
graph.add_edge(("TX", "NY"),1200)
graph.add_edge(("ALB", "NY"),800)
g = graph.adj_mat()
def bfs_connected_components(graph):
connected_components = []
nodes = graph.keys()
while len(nodes)!=0:
start_node = nodes.pop()
queue = [start_node] #FIFO
visited = [start_node]
while len(queue)!=0:
start = queue[0]
queue.remove(start)
neighbours = graph[start]
for neighbour,_ in neighbours.iteritems():
if neighbour not in visited:
queue.append(neighbour)
visited.append(neighbour)
nodes.remove(neighbour)
connected_components.append(visited)
return connected_components
print bfs_connected_components(g)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment