forked from iRupam/NewtonSchoolInfinityJune21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
46 lines (37 loc) · 1.28 KB
/
DFS.java
File metadata and controls
46 lines (37 loc) · 1.28 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
package InfinityJune21.Graph;
import java.util.ArrayList;
public class DFS {
static int V = 5;
static ArrayList<ArrayList<Integer>> adjacencyList = new ArrayList<ArrayList<Integer>>();
static void addEdge(ArrayList<ArrayList<Integer>> adjacencyList, int u, int v) {
adjacencyList.get(u).add(v);
adjacencyList.get(v).add(u);
}
static void dfs(int source) {
boolean visited[] = new boolean[V];
dfsUtility(source, visited);
}
static void dfsUtility(int source, boolean visited[]) {
visited[source] = true;
System.out.print(source + " ");
ArrayList<Integer> adjacent = adjacencyList.get(source);
for(Integer adj : adjacent) {
if(!visited[adj]) {
dfsUtility(adj, visited);
}
}
}
public static void main(String[] args) {
for(int i = 0; i < V; i++) {
adjacencyList.add(new ArrayList<Integer>());
}
addEdge(adjacencyList, 0, 1);
addEdge(adjacencyList, 0, 4);
addEdge(adjacencyList, 1, 2);
addEdge(adjacencyList, 1, 3);
addEdge(adjacencyList, 1, 4);
addEdge(adjacencyList, 2, 3);
addEdge(adjacencyList, 3, 4);
dfs(0);
}
}