BFS - Given undirected graph
1. Find shortest path and distance from a node to remaining nodes
2. Detect Cycle
SOURCE CODE:
import java.util.LinkedList;
import java.util.Queue;
class Graph {
int V;
LinkedList<Integer>[] adjList;
Graph(int V) {
this.V = V;
adjList = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjList[i] = new LinkedList<>();
}
}
void addEdge(int src, int dest) {
adjList[src].add(dest);
adjList[dest].add(src);
}
void BFS_ShortestPath(int src) {
boolean[] visited = new boolean[V];
int[] distance = new int[V];
Queue<Integer> queue = new LinkedList<>();
visited[src] = true;
distance[src] = 0;
queue.add(src);
while (!queue.isEmpty()) {
int u = queue.poll();
System.out.print(u + " ");
for (int v : adjList[u]) {
if (!visited[v]) {
visited[v] = true;
distance[v] = distance[u] + 1;
queue.add(v);
}
}
}
System.out.println("\nShortest distances from source " + src);
for (int i = 0; i < V; i++) {
System.out.println(i + " -> " + distance[i]);
}
}
boolean BFS_DetectCycle() {
boolean[] visited = new boolean[V];
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < V; i++) {
if (!visited[i]) {
visited[i] = true;
queue.add(i);
while (!queue.isEmpty()) {
int u = queue.poll();
for (int v : adjList[u]) {
if (!visited[v]) {
visited[v] = true;
queue.add(v);
} else {
return true;
}
}
}
}
}
return false;
}
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 5);
graph.BFS_ShortestPath(0);
if (graph.BFS_DetectCycle()) {
System.out.println("Cycle detected");
} else {
System.out.println("No cycle detected");
}
}
}
OUTPUT: