2 bfs
Sun Nov 26 2023 17:36:42 GMT+0000 (Coordinated Universal Time)
Saved by
@jack
import java.util.Iterator;
import java.util.LinkedList;
class Graph {
private int V;
private LinkedList<Integer>[] adj;
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList<>();
}
void addEdge(int u, int v) {
adj[u].add(v);
}
void BFS(int s) {
boolean vis[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList<>();
vis[s] = true;
queue.add(s);
while (!queue.isEmpty()) {
s = queue.poll();
System.out.print(s + " ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!vis[n]) {
vis[n] = true;
queue.add(n);
}
}
}
}
public static void main(String args[]) {
Graph g = new Graph(8);
g.addEdge(0, 1);
g.addEdge(3, 2);
g.addEdge(5, 2);
g.addEdge(3, 5);
g.addEdge(3, 4);
g.addEdge(4, 6);
g.addEdge(6, 3);
g.addEdge(6, 7);
g.addEdge(7, 1);
System.out.print("BFS traversal from vertex 0 is: ");
g.BFS(0);
}
}
content_copyCOPY
https://www.programiz.com/java-programming/online-compiler/
Comments