-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph_Practice.java
More file actions
65 lines (52 loc) · 1.76 KB
/
Graph_Practice.java
File metadata and controls
65 lines (52 loc) · 1.76 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
61
62
63
64
65
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Graph_Practice {
public static void createGraph(ArrayList<Edge> graph[]) {
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<Edge>();
}
graph[0].add(new Edge(0, 1, 2));
graph[0].add(new Edge(0, 2, 4));
graph[1].add(new Edge(1, 2, 1));
graph[1].add(new Edge(1, 3, 7));
graph[2].add(new Edge(2, 3, 3));
graph[3].add(new Edge(3, 4, 5));
}
public static void BFS(ArrayList<Edge> graph[], int startVertex) {
boolean[] visited = new boolean[graph.length];
Queue<Integer> queue = new LinkedList<>();
visited[startVertex] = true;
queue.add(startVertex);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
ArrayList<Edge> edges = graph[vertex];
for (int i = 0; i < edges.size(); i++) {
Edge edge = edges.get(i);
int destVertex = edge.dest;
if (!visited[destVertex]) {
visited[destVertex] = true;
queue.add(destVertex);
}
}
}
}
public static void main(String[] args) {
int vertex = 5;
ArrayList<Edge> graph[] = new ArrayList[vertex];
createGraph(graph);
System.out.println("Breadth-First Traversal starting from vertex 0:");
BFS(graph, 0);
}
}
class Edge {
int src;
int dest;
int weight;
public Edge(int src, int dest, int weight) {
this.src = src;
this.dest = dest;
this.weight = weight;
}
}