Skip to content

Commit 5eb9031

Browse files
committed
Create DisjointedGraphTraversal.java
1 parent 22329fa commit 5eb9031

File tree

1 file changed

+170
-0
lines changed

1 file changed

+170
-0
lines changed
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
import java.util.*;
2+
3+
/**
4+
* DisjointedGraphTraversal
5+
*
6+
* Utility class that demonstrates traversal algorithms (DFS and BFS) for a graph
7+
* that may consist of multiple disjoint components. The graph is represented as
8+
* an adjacency list: a List<List<Integer>> where each index represents a node
9+
* (0..n-1) and the inner lists contain neighboring node indices.
10+
*
11+
* Notes and conventions:
12+
* - The class methods print traversal order to standard output.
13+
* - The graph is treated as an undirected graph in the example usage, but the
14+
* traversal code itself works for any directed/undirected adjacency-list
15+
* representation.
16+
* - All methods expect a non-null List<List<Integer>> of size n. Each inner
17+
* list may be empty when a node has no neighbors.
18+
*
19+
* Public methods:
20+
* - dfs(boolean[] visited, List<List<Integer>> graph)
21+
* Performs a complete depth-first traversal over all nodes in the graph,
22+
* visiting each connected component starting from the smallest unvisited
23+
* index. This method uses the recursive helper dfsUtil to visit nodes in a
24+
* component. The provided visited array is mutated to record visited nodes.
25+
*
26+
* @param visited boolean array of length >= graph.size(); visited[i] is true
27+
* when node i has already been visited. The array is
28+
* modified by the method.
29+
* @param graph adjacency list representation of the graph
30+
*
31+
* - getCountOfComponents(boolean[] visited, List<List<Integer>> graph)
32+
* Traverses the graph and counts the number of connected components. Each
33+
* time an unvisited node is found, it starts a DFS (via dfsUtil) to mark all
34+
* nodes in that component. The method prints each visited node (as a side
35+
* effect) and prints the final count of connected components.
36+
*
37+
* @param visited boolean array to track visited nodes; this array is
38+
* modified by the method.
39+
* @param graph adjacency list representation of the graph
40+
*
41+
* - bfs(boolean[] visited, List<List<Integer>> graph)
42+
* Performs a complete breadth-first traversal over all nodes in the graph.
43+
* Note: this implementation reinitializes the visited array internally to a
44+
* new boolean[graph.size()], so the visited parameter passed in by the
45+
* caller is effectively ignored. The method prints nodes in BFS order.
46+
*
47+
* @param visited boolean array (ignored and overwritten in current
48+
* implementation)
49+
* @param graph adjacency list representation of the graph
50+
*
51+
* - main(String[] args)
52+
* Example/demo entry point that builds a small disjoint graph, prints the
53+
* adjacency lists, and demonstrates DFS-based component counting and BFS
54+
* traversal.
55+
*
56+
* Helper (private) method:
57+
* - dfsUtil(int node, boolean[] visited, List<List<Integer>> graph)
58+
* Recursive helper that performs the standard DFS visit for a single
59+
* connected component, printing nodes as they are discovered.
60+
*
61+
* @param node index of the start node to visit
62+
* @param visited boolean array that is updated as nodes are visited
63+
* @param graph adjacency list representation of the graph
64+
*
65+
* Complexity:
66+
* - Time: O(V + E) for full traversal of the graph (V = number of nodes,
67+
* E = number of edges) for both DFS and BFS.
68+
* - Space: O(V) for the visited array; DFS additionally uses recursion stack
69+
* space up to O(V) in the worst case.
70+
*
71+
* Usage hints:
72+
* - If you want the bfs method to respect an externally-provided visited array,
73+
* remove the internal reinitialization (visited = new boolean[graph.size()]).
74+
* - To adapt for 1-based node indices or non-integer node labels, map labels to
75+
* contiguous integer indices before constructing the adjacency list.
76+
*/
77+
public class DisjointedGraphTraversal {
78+
79+
public static void dfs(boolean visited[], List<List<Integer>> graph) {
80+
// Connected components traversal
81+
// for(List<Integer> neigbhour : graph){
82+
// for(int node: neigbhour){
83+
// if(!visited[node]){
84+
// visited[node] = true;
85+
// System.out.print(node+" ");
86+
// dfs(visited, graph);
87+
// }
88+
// }
89+
// }
90+
// Complete traversal of disjointed graph
91+
for (int i = 0; i < graph.size(); i++) {
92+
if (!visited[i]) {
93+
dfsUtil(i, visited, graph);
94+
}
95+
}
96+
}
97+
98+
private static void dfsUtil(int node, boolean visited[], List<List<Integer>> graph) {
99+
System.out.print(node + " ");
100+
visited[node] = true;
101+
for (int neighbor : graph.get(node)) {
102+
if (!visited[neighbor]) {
103+
dfsUtil(neighbor, visited, graph);
104+
}
105+
}
106+
}
107+
108+
public static void getCountOfComponents(boolean visited[], List<List<Integer>> graph) {
109+
int count = 0;
110+
for (int i = 0; i < graph.size(); i++) {
111+
if (!visited[i]) {
112+
count++;
113+
dfsUtil(i, visited, graph);
114+
}
115+
}
116+
System.out.println("\nNumber of connected components: " + count);
117+
}
118+
119+
public static void bfs(boolean visited[], List<List<Integer>> graph) {
120+
visited = new boolean[graph.size()];
121+
Queue<Integer> queue = new LinkedList();
122+
for (int i = 0; i < graph.size(); i++) {
123+
if (!visited[i]) {
124+
visited[i] = true;
125+
queue.add(i);
126+
while (!queue.isEmpty()) {
127+
int node = queue.poll();
128+
System.out.print(node + " ");
129+
for (int neighbor : graph.get(node)) {
130+
if (!visited[neighbor]) {
131+
visited[neighbor] = true;
132+
queue.add(neighbor);
133+
}
134+
}
135+
}
136+
}
137+
}
138+
}
139+
140+
public static void main(String[] args) {
141+
List<List<Integer>> disjointedGraph = new ArrayList<>();
142+
for (int i = 0; i < 5; i++) {
143+
disjointedGraph.add(new ArrayList<>());
144+
}
145+
disjointedGraph.get(0).add(1);
146+
disjointedGraph.get(1).add(0);
147+
disjointedGraph.get(0).add(4);
148+
disjointedGraph.get(4).add(0);
149+
150+
disjointedGraph.get(1).add(4);
151+
disjointedGraph.get(4).add(1);
152+
disjointedGraph.get(1).add(3);
153+
disjointedGraph.get(3).add(1);
154+
for (int i = 0; i < 5; i++) {
155+
System.out.print(i + ": ");
156+
for (int neighbor : disjointedGraph.get(i)) {
157+
System.out.print(neighbor + " ");
158+
}
159+
System.out.println();
160+
}
161+
boolean visited[] = new boolean[5];
162+
System.out.println("DFS Traversal of Disjointed Graph:");
163+
// dfs(visited, disjointedGraph);
164+
visited = new boolean[5];
165+
getCountOfComponents(visited, disjointedGraph);
166+
System.out.println("BFS Traversal of Disjointed Graph:");
167+
bfs(visited, disjointedGraph);
168+
169+
}
170+
}

0 commit comments

Comments
 (0)