-
Notifications
You must be signed in to change notification settings - Fork 21k
Expand file tree
/
Copy pathDFSOFDIRECTEDGRAPH.java
More file actions
58 lines (47 loc) · 1.37 KB
/
DFSOFDIRECTEDGRAPH.java
File metadata and controls
58 lines (47 loc) · 1.37 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
import java.util.*;
class Solution {
// Function to perform DFS traversal
public void dfs(int v, List<Integer>[] adj,
boolean[] visited,
List<Integer> result) {
// Mark current node as visited
visited[v] = true;
// Store node in result
result.add(v);
// Traverse all neighbours
for (int u : adj[v]) {
if (!visited[u]) {
dfs(u, adj, visited, result);
}
}
}
}
public class Main {
public static void main(String[] args) {
// Number of vertices
int V = 5;
// Adjacency list
List<Integer>[] adj = new ArrayList[V];
for (int i = 0; i < V; i++) {
adj[i] = new ArrayList<>();
}
adj[0].addAll(Arrays.asList(1, 2));
adj[1].addAll(Arrays.asList(0, 3));
adj[2].addAll(Arrays.asList(0, 4));
adj[3].add(1);
adj[4].add(2);
// Visited array
boolean[] visited = new boolean[V];
// Result list
List<Integer> result = new ArrayList<>();
// Create object
Solution sol = new Solution();
// Run DFS from node 0
sol.dfs(0, adj, visited, result);
// Print traversal
for (int x : result) {
System.out.print(x + " ");
}
System.out.println();
}
}