- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDFSRecursion.java
More file actions
Latest commit
47 lines (41 loc) · 1.34 KB
/
Copy pathDFSRecursion.java
File metadata and controls
47 lines (41 loc) · 1.34 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
importjava.util.LinkedList;
publicclassDFSRecursion {
staticclassGraph{
intvertices;
LinkedList<Integer>[] adjList;
Graph(intvertices){
this.vertices = vertices;
adjList = newLinkedList[vertices];
for (inti = 0; i <vertices ; i++) {
adjList[i] = newLinkedList<>();
}
}
publicvoidaddEgde(intsource, intdestination){
adjList[source].add(destination);
adjList[destination].add(source);
}
publicvoidDFSRecursion(intstartVertex){
boolean [] visited = newboolean[vertices];
dfs(startVertex, visited);
}
publicvoiddfs(intstart, boolean [] visited){
visited[start] = true;
System.out.print(start + " ");
for (inti = 0; i <adjList[start].size() ; i++) {
intdestination = adjList[start].get(i);
if(!visited[destination])
dfs(destination,visited);
}
}
}
publicstaticvoidmain(String[] args) {
intvertices = 6;
Graphgraph = newGraph(vertices);
graph.addEgde(0, 1);
graph.addEgde(0, 2);
graph.addEgde(0, 3);
graph.addEgde(1, 2);
graph.addEgde(2, 4);
graph.DFSRecursion(0);
}
}