- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathBreadthFirstSearch.java
More file actions
Latest commit
75 lines (59 loc) · 1.9 KB
/
Copy pathBreadthFirstSearch.java
File metadata and controls
75 lines (59 loc) · 1.9 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
66
67
68
69
70
71
72
73
74
importjava.util.*;
importjava.io.*;
publicclassBreadthFirstSearch {
classGraph {
privateintv; // No. of vertices
privateLinkedList<Integer> adj[]; // Adjacency Lists
Graph(intv) {
this.v = v;
adj = newLinkedList[v];
for (inti = 0; i < v; ++i)
adj[i] = newLinkedList<Integer>();
}
voidaddEdge(intv, intw) {
adj[v].add(w);
adj[w].add(v);
}
// BFS traversal from a given source node 's'
voidBFS(ints) {
booleanvisited[] = newboolean[v];
// Create a queue for BFS traversal
LinkedList<Integer> queue = newLinkedList<Integer>();
// Mark the current node as visited and add into queue
queue.add(s);
visited[s] = true;
while (!queue.isEmpty()) {
// Remove a vertex from queue and print it
intcurr = queue.poll();
System.out.print(curr+ " ");
// Get all adjacent vertices of the dequeued vertex s.
// If an adjacent has not been visited, then mark it visited and enqueue it
for (intnbr : adj[curr]) {
if (!visited[nbr]) {
queue.add(nbr);
visited[nbr] = true;
}
}
}
}
}
publicstaticvoidmain(Stringargs[]) throwsIOException {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
System.out.println("Enter the no. of vertices and edges:");
String[] inp = br.readLine().split(" ");
intN = Integer.parseInt(inp[0]);
intM = Integer.parseInt(inp[1]);
BreadthFirstSearchobj = newBreadthFirstSearch();
Graphg = obj.newGraph(N);
for (inti = 1; i <= M; i++) {
System.out.println("Enter edge No. " + i + ":");
inp = br.readLine().split(" ");
intu = Integer.parseInt(inp[0]);
intv = Integer.parseInt(inp[1]);
g.addEdge(u, v);
}
System.out.println("Enter source vertex: ");
ints = Integer.parseInt(br.readLine());
g.BFS(s);
}
}