forked from ossamamehmood/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DfsGraphTraversal.java
42 lines (34 loc) 路 1.06 KB
/
DfsGraphTraversal.java
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
import java.util.LinkedList;
import java.util.Stack;
class DfsGraphTraversal {
private int V; // Number of vertices
private LinkedList<Integer> adjList[]; // Adjacency list
public DfsGraphTraversal(int v) {
V = v;
adjList = new LinkedList[v];
for (int i = 0; i < v; i++) {
adjList[i] = new LinkedList<>();
}
}
// Add an edge to the graph
public void addEdge(int v, int w) {
adjList[v].add(w);
}
// Depth-First Search (DFS) traversal
public void DFS(int startVertex) {
boolean[] visited = new boolean[V];
Stack<Integer> stack = new Stack<>();
visited[startVertex] = true;
stack.push(startVertex);
while (!stack.isEmpty()) {
startVertex = stack.pop();
System.out.print(startVertex + " ");
for (Integer neighbor : adjList[startVertex]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
stack.push(neighbor);
}
}
}
}
}