-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathGraphExample.java
81 lines (66 loc) · 2.04 KB
/
GraphExample.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.*;
import java.util.Queue;
public class GraphExample {
private int vertices;
private LinkedList<Integer> [] adjList;
// Constructor
public GraphExample(int vertices) {
this.vertices = vertices;
adjList = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adjList[i] = new LinkedList<>();
}
}
// Add an edge
public void addEdge(int src, int dest) {
adjList[src].add(dest);
adjList[dest].add(src); // for undirected graph
}
// BFS Traversal
public void bfs(int startVertex) {
boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
visited[startVertex] = true;
queue.add(startVertex);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
for(int adj : adjList[vertex]) {
if (!visited[adj]) {
visited[adj] = true;
queue.add(adj);
}
}
}
}
// DFS traversal
public void dfs(int startVertex) {
boolean[] visited = new boolean[vertices];
dfsHelper(startVertex, visited);
}
// helper function for DFS
public void dfsHelper(int vertex, boolean[] visited) {
visited[vertex] = true;
System.out.print(vertex + " ");
for (int adj : adjList[vertex]) {
if (!visited[adj]) {
dfsHelper(adj, visited);
}
}
}
// Main Method to test
public static void main(String[] args) {
GraphExample graph = new GraphExample(5);
graph.addEdge(0, 1);
graph.addEdge(0, 4);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
System.out.println("BFS Traversal starting from node 0:");
graph.bfs(0);
System.out.println("\nDFS Traversal starting from node 0:");
graph.dfs(0);
}
}