import java.util.*;
class Graph {
private Map<Integer, List<Integer>> adjList = new HashMap<>();
public void addEdge(int u, int v) {
adjList.computeIfAbsent(u, k -> new ArrayList<>()).add(v);
}
public List<Integer> shortestPath(int start, int end) {
Queue<Integer> queue = new LinkedList<>();
Map<Integer, Integer> parent = new HashMap<>();
Set<Integer> visited = new HashSet<>();
queue.add(start);
visited.add(start);
parent.put(start, null);
while (!queue.isEmpty()) {
int current = queue.poll();
if (current == end) break;
for (int neighbor : adjList.getOrDefault(current, Collections.emptyList())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
parent.put(neighbor, current);
queue.add(neighbor);
}
}
}
List<Integer> path = new ArrayList<>();
Integer step = end;
while (step != null) {
path.add(step);
step = parent.get(step);
}
Collections.reverse(path);
if (!path.isEmpty() && path.get(0) == start) return path;
else return Collections.emptyList();
}
public static void main(String[] args) {
Graph g = new Graph();
g.addEdge(1, 2);
g.addEdge(2, 3);
g.addEdge(3, 6);
g.addEdge(6, 5);
g.addEdge(5, 4);
g.addEdge(4, 1);
g.addEdge(2, 5);
List<Integer> path = g.shortestPath(1, 5);
if (path.isEmpty()) {
System.out.println("No path found");
} else {
for (int i = 0; i < path.size(); i++) {
System.out.print(path.get(i));
if (i != path.size() - 1) System.out.print(" -> ");
}
System.out.println(" -> null");
}
}
}queue.add(start);
visited.add(start);
parent.put(start, null);
Initialize BFS with start node marked visited and no parent
while (!queue.isEmpty()) {
int current = queue.poll();
if (current == end) break;
Process nodes in BFS order, stop when end node is reached
for (int neighbor : adjList.getOrDefault(current, Collections.emptyList())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
parent.put(neighbor, current);
queue.add(neighbor);
}
}
Explore neighbors, mark visited, track parent for path reconstruction
while (step != null) {
path.add(step);
step = parent.get(step);
}
Reconstruct path from end to start using parent links