-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathCountConnectedComponents.java
71 lines (59 loc) · 1.56 KB
/
CountConnectedComponents.java
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
import java.util.Iterator;
import java.util.LinkedList;
public class CountConnectedComponents {
public static void main(String args[])
{
Graph g = new Graph(9);
// connected
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
// 4 is self connected
// connected
g.addEdge(6, 5);
g.addEdge(7, 5);
g.addEdge(5, 8);
System.out.println("Number of connected graphs: " + g.count());
}
}
class Graph {
private int numVertices;
private LinkedList<Integer> adj[];
private boolean visited[];
public Graph(int vertices) {
numVertices = vertices;
adj = new LinkedList[vertices];
for (int i = 0; i < vertices; i++)
adj[i] = new LinkedList<Integer>();
}
void addEdge(int src, int dest) {
// change the directed graph to undirected graph
if (src != dest) {
adj[src].add(dest);
adj[dest].add(src);
}
}
int count() {
int ret = 0;
visited = new boolean[numVertices];
for (int i = 0; i < numVertices; ++i) {
if(!visited[i]) {
DFS(i);
++ret;
}
}
return ret;
}
void DFS(int vertex) {
visited[vertex] = true;
Iterator ite = adj[vertex].listIterator();
while (ite.hasNext()) {
int adj = (int) ite.next();
if (!visited[adj])
DFS(adj);
}
}
}