I am trying to get all the connected components in a graph and print them out. I am going through each node of the graph and performing a depth-first-search(DFS) starting from that node. Here is my code:
graph = {
'a': ['b'],
'b': ['c'],
'c': ['d'],
'd': [],
'e': ['f'],
'f': []
}
def DFS(graph, start_node, stack = [], visited = []):
stack.append(start_node)
while stack:
v = stack.pop()
if v not in visited:
visited.append(v)
for neighbor in graph[v]:
stack.append(neighbor)
return visited
def dfs_get_connected_components_util(graph):
visited = []
for node in graph:
if node not in visited:
DFS_algo = DFS(graph, node)
print(DFS_algo)
visited = DFS_algo
print(dfs_get_connected_components_util(graph))
According to my graph, there are two connected components, a -> b -> c -> d and e -> f
Instead I get the following print out:
['c', 'd']
['c', 'd', 'a', 'b']
['c', 'd', 'a', 'b', 'f']
['c', 'd', 'a', 'b', 'f', 'e']
I can't seem to figure out what I'm doing wrong in my connected components function. I guess this may be more of a python question.