NAME- SYED SADIA ZOYA
REG NO- 23BCE9358
ASSIGNMENT- 12
1. import java.util.*;
public class CityNavigation {
private Map<Integer, List<Integer>> graph;
public CityNavigation() {
graph = new HashMap<>();
}
public void addRoad(int from, int to) {
graph.putIfAbsent(from, new ArrayList<>());
graph.putIfAbsent(to, new ArrayList<>());
graph.get(from).add(to);
graph.get(to).add(from);
}
public List<Integer> shortestPath(int start, int end) {
Queue<List<Integer>> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.add(Arrays.asList(start));
visited.add(start);
while (!queue.isEmpty()) {
List<Integer> path = queue.poll();
int node = path.get(path.size() - 1);
if (node == end) return path;
for (int neighbor : graph.getOrDefault(node, new ArrayList<>())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
List<Integer> newPath = new ArrayList<>(path);
newPath.add(neighbor);
queue.add(newPath);
}
}
}
return Arrays.asList(-1);
}
public List<Integer> intersectionsWithinHops(int start, int hops) {
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
List<Integer> result = new ArrayList<>();
queue.add(start);
visited.add(start);
int level = 0;
while (!queue.isEmpty() && level <= hops) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int node = queue.poll();
if (level <= hops) result.add(node);
for (int neighbor : graph.getOrDefault(node, new ArrayList<>())) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
level++;
}
return result;
}
public static void main(String[] args) {
CityNavigation navigation = new CityNavigation();
navigation.addRoad(1, 2);
navigation.addRoad(1, 3);
navigation.addRoad(2, 4);
navigation.addRoad(3, 4);
navigation.addRoad(3, 5);
navigation.addRoad(4, 6);
System.out.println("Shortest Path from 1 to 6: " +
navigation.shortestPath(1, 6));
System.out.println("Intersections within 2 hops from 1: " +
navigation.intersectionsWithinHops(1, 2));
}
}
OUTPUT: