-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconnected_components.py
More file actions
78 lines (57 loc) · 1.96 KB
/
connected_components.py
File metadata and controls
78 lines (57 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Connected Components in a Graph
A connected component is a subgraph in which any two vertices are connected
by paths, and which is connected to no additional vertices in the supergraph.
This algorithm finds all connected components in an undirected graph using DFS.
Time Complexity: O(V + E) where V is vertices and E is edges
Space Complexity: O(V)
"""
def find_connected_components(graph):
"""
Finds all connected components in an undirected graph.
Args:
graph: Dictionary representing adjacency list {node: [neighbors]}
Returns:
List of components, where each component is a list of vertices
"""
visited = set()
components = []
def dfs(node, component):
"""DFS helper to explore a connected component."""
visited.add(node)
component.append(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
dfs(neighbor, component)
# Find all components
for node in graph:
if node not in visited:
component = []
dfs(node, component)
components.append(component)
return components
def count_connected_components(graph):
"""
Counts the number of connected components in a graph.
Args:
graph: Dictionary representing adjacency list
Returns:
Number of connected components
"""
return len(find_connected_components(graph))
# Example usage
if __name__ == "__main__":
# Example graph with 3 connected components
graph = {
'A': ['B', 'C'],
'B': ['A', 'C'],
'C': ['A', 'B'],
'D': ['E'],
'E': ['D'],
'F': []
}
print("Connected components:")
components = find_connected_components(graph)
for i, component in enumerate(components, 1):
print(f" Component {i}: {component}")
print(f"\nTotal number of components: {count_connected_components(graph)}")