Solution: Find All Connected Components of a Graph
This review provides a detailed analysis of the solution to find all connected components of a graph.
We'll cover the following...
Solution:
def connected_components(graph):"""Function to find the connected components:param graph: The graph:return: returns a list of connected components"""visited = []result = []for i in range(graph.V):visited.append(False)for v in range(graph.V):if not visited[v]:result.append(dfs(g, v, visited))return resultdef dfs(g, source, visited):"""Function to print a DFS of graph:param graph: The graph:param source: starting vertex:return: returns the traversal in a list"""graph = copy.deepcopy(g)# Create a stack for DFSstack = []# Result stringresult = []# Push the sourcestack.append(source)while stack:# Pop a vertex from stacksource = stack[-1]stack.pop()if not visited[source]:result.append(source)visited[source] = True# Get all adjacent vertices of the popped vertex source.# If a adjacent has not been visited, then push itwhile graph.graph[source] is not None:data = graph.graph[source].vertexif not visited[data]:stack.append(data)graph.graph[source] = graph.graph[source].nextreturn result# Main program to test above functionif __name__ == "__main__":g = Graph(7)g.add_edge(0, 1)g.add_edge(1, 2)g.add_edge(2, 3)g.add_edge(3, 0)g.add_edge(4, 5)g.add_edge(5, 6)result = connected_components(g)print("Following are connected components")print(result)
Explanation
We can ...
Access this course and 1400+ top-rated courses and projects.