-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
60 lines (44 loc) · 1.54 KB
/
DFS.java
File metadata and controls
60 lines (44 loc) · 1.54 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
59
60
import java.util.LinkedList;
public class DFS {
private static class Graph {
private int vertices;
private LinkedList<Integer>[] adjacencyList;
public Graph(int vertices) {
this.vertices = vertices;
adjacencyList = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adjacencyList[i] = new LinkedList<>();
}
}
public void addEdge(int source, int destination) {
adjacencyList[source].add(destination);
}
public void dfs(int startVertex) {
boolean[] visited = new boolean[vertices];
dfsUtil(startVertex, visited);
}
private void dfsUtil(int currentVertex, boolean[] visited) {
visited[currentVertex] = true;
System.out.print(currentVertex + " ");
LinkedList<Integer> adjacentVertices = adjacencyList[currentVertex];
for (int adjacentVertex : adjacentVertices) {
if (!visited[adjacentVertex]) {
dfsUtil(adjacentVertex, visited);
}
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
graph.addEdge(3, 5);
System.out.println("DFS traversal starting from vertex 0:");
graph.dfs(0);
System.out.println();
}
}