-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay27.java
More file actions
78 lines (65 loc) · 2.55 KB
/
Day27.java
File metadata and controls
78 lines (65 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.*;
class Graph {
private int vertices;
private Map<Integer, List<Integer>> adjacencyList;
public Graph(int vertices) {
this.vertices = vertices;
this.adjacencyList = new HashMap<>();
for (int i = 0; i < vertices; i++) {
adjacencyList.put(i, new LinkedList<>());
}
}
public void addEdge(int source, int destination) {
adjacencyList.get(source).add(destination);
adjacencyList.get(destination).add(source); // For undirected graph
}
public List<Integer> shortestPath(int startVertex, int endVertex) {
Queue<Integer> queue = new LinkedList<>();
Map<Integer, Integer> parentMap = new HashMap<>();
Set<Integer> visited = new HashSet<>();
queue.add(startVertex);
visited.add(startVertex);
while (!queue.isEmpty()) {
int currentVertex = queue.poll();
for (int neighbor : adjacencyList.get(currentVertex)) {
if (!visited.contains(neighbor)) {
queue.add(neighbor);
visited.add(neighbor);
parentMap.put(neighbor, currentVertex);
if (neighbor == endVertex) {
// Reconstruct the path
List<Integer> path = new ArrayList<>();
int vertex = endVertex;
while (vertex != startVertex) {
path.add(vertex);
vertex = parentMap.get(vertex);
}
path.add(startVertex);
Collections.reverse(path);
return path;
}
}
}
}
return Collections.emptyList(); // No path found
}
}
public class Day27 {
public static void main(String[] args) {
Graph graph = new Graph(7);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 5);
graph.addEdge(2, 6);
int startVertex = 0;
int endVertex = 4;
List<Integer> shortestPath = graph.shortestPath(startVertex, endVertex);
if (!shortestPath.isEmpty()) {
System.out.println("Shortest path from " + startVertex + " to " + endVertex + ": " + shortestPath);
} else {
System.out.println("No path found from " + startVertex + " to " + endVertex);
}
}
}