Master shortest path algorithms in graphs and learn how to efficiently traverse graph structures. Understand the applications of BFS in pathfinding and distance calculations.
public class Graph {
private Map> adjacencyList = new HashMap<>();
public Map shortestPaths(T start) {
Map distances = new HashMap<>();
Queue queue = new LinkedList<>();
Set visited = new HashSet<>();
// Initialize distances
distances.put(start, 0);
queue.offer(start);
visited.add(start);
while (!queue.isEmpty()) {
T current = queue.poll();
for (T neighbor : adjacencyList.get(current)) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
distances.put(neighbor, distances.get(current) + 1);
queue.offer(neighbor);
}
}
}
return distances;
}
public List findPath(T start, T end) {
Map parentMap = new HashMap<>();
Queue queue = new LinkedList<>();
Set visited = new HashSet<>();
queue.offer(start);
visited.add(start);
while (!queue.isEmpty() && !queue.peek().equals(end)) {
T current = queue.poll();
for (T neighbor : adjacencyList.get(current)) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
parentMap.put(neighbor, current);
queue.offer(neighbor);
}
}
}
if (!visited.contains(end)) {
return Collections.emptyList(); // No path exists
}
// Reconstruct path
List path = new ArrayList<>();
T current = end;
while (current != null) {
path.add(0, current);
current = parentMap.get(current);
}
return path;
}
}
public class PathUtils {
public static boolean hasPath(Graph graph, T start, T end) {
return !graph.findPath(start, end).isEmpty();
}
public static int shortestDistance(Graph graph, T start, T end) {
Map distances = graph.shortestPaths(start);
return distances.getOrDefault(end, -1);
}
public static Set reachableNodes(Graph graph, T start) {
return new HashSet<>(graph.shortestPaths(start).keySet());
}
}
For additional hands-on practice and in-depth exercises on graph algorithms, check out our comprehensive guided project:
Practice fundamental path finding techniques:
Solve more complex path finding challenges:
Apply path finding to complex scenarios: