1. BFS & DFS (Combined)
This version includes the shared graph and visited array management.
Java
import java.util.*;
public class Main {
static void bfs(int start, ArrayList<Integer>[] adj, boolean[] vis) {
Queue<Integer> q = new LinkedList<>();
q.add(start);
vis[start] = true;
while (!q.isEmpty()) {
int u = q.poll();
System.out.print(u + " ");
for (int v : adj[u]) {
if (!vis[v]) {
vis[v] = true;
q.add(v);
}
}
}
}
static void dfs(int u, ArrayList<Integer>[] adj, boolean[] vis) {
vis[u] = true;
System.out.print(u + " ");
for (int v : adj[u]) {
if (!vis[v]) {
dfs(v, adj, vis);
}
}
}
public static void main(String[] args) {
int n = 6;
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
adj[1].add(2); adj[2].add(1);
adj[1].add(3); adj[3].add(1);
adj[2].add(4); adj[4].add(2);
adj[2].add(5); adj[5].add(2);
boolean[] vis = new boolean[n];
System.out.println("BFS Traversal:");
bfs(1, adj, vis);
Arrays.fill(vis, false);
System.out.println("\nDFS Traversal:");
dfs(1, adj, vis);
}
}
2. BFS Shortest Path (Unweighted)
Finds the number of edges from the source to every other node.
Java
import java.util.*;
public class Main {
static int[] bfsShortestPath(int start, ArrayList<Integer>[] adj, int n) {
int[] dist = new int[n];
Arrays.fill(dist, -1);
Queue<Integer> q = new LinkedList<>();
q.add(start);
dist[start] = 0;
while (!q.isEmpty()) {
int u = q.poll();
for (int v : adj[u]) {
if (dist[v] == -1) {
dist[v] = dist[u] + 1;
q.add(v);
}
}
}
return dist;
}
public static void main(String[] args) {
int n = 5;
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
adj[0].add(1); adj[1].add(0);
adj[0].add(2); adj[2].add(0);
adj[1].add(3); adj[3].add(1);
adj[3].add(4); adj[4].add(3);
int[] res = bfsShortestPath(0, adj, n);
for(int i=0; i<n; i++) System.out.println("Node " + i + " distance: " + res[i]);
}
}
}