Applying Weighted Edges in Java Graph Algorithms
Shortest Path Algorithms
One of the most common applications of weighted graphs is finding the shortest path between two vertices. The Dijkstra's algorithm is a popular algorithm for solving this problem. Here's an example implementation in Java:
class WeightedGraph {
// ...
public int[] dijkstra(int source) {
int[] distances = new int[numVertices];
Arrays.fill(distances, Integer.MAX_VALUE);
distances[source] = 0;
PriorityQueue<Pair<Integer, Integer>> pq = new PriorityQueue<>((a, b) -> a.getKey() - b.getKey());
pq.offer(new Pair<>(0, source));
while (!pq.isEmpty()) {
int currentVertex = pq.poll().getValue();
for (Pair<Integer, Integer> neighbor : adjacencyList[currentVertex]) {
int neighborVertex = neighbor.getKey();
int weight = neighbor.getValue();
if (distances[neighborVertex] > distances[currentVertex] + weight) {
distances[neighborVertex] = distances[currentVertex] + weight;
pq.offer(new Pair<>(distances[neighborVertex], neighborVertex));
}
}
}
return distances;
}
}
This implementation of Dijkstra's algorithm uses a priority queue to efficiently explore the graph and find the shortest paths from the source vertex to all other vertices.
Minimum Spanning Tree Algorithms
Another common application of weighted graphs is finding the minimum spanning tree (MST) of a graph. The Kruskal's algorithm and the Prim's algorithm are two popular algorithms for this purpose. Here's an example of Kruskal's algorithm in Java:
class WeightedGraph {
// ...
public List<Pair<Integer, Integer>> kruskalMST() {
List<Pair<Integer, Integer>> mst = new ArrayList<>();
List<Pair<Integer, Integer>> edges = new ArrayList<>();
for (int i = 0; i < numVertices; i++) {
for (Pair<Integer, Integer> neighbor : adjacencyList[i]) {
int neighborVertex = neighbor.getKey();
int weight = neighbor.getValue();
if (i < neighborVertex) {
edges.add(new Pair<>(i, neighborVertex));
}
}
}
edges.sort((a, b) -> Integer.compare(b.getValue(), a.getValue()));
UnionFind uf = new UnionFind(numVertices);
for (Pair<Integer, Integer> edge : edges) {
int source = edge.getKey();
int destination = edge.getValue();
if (uf.find(source) != uf.find(destination)) {
uf.union(source, destination);
mst.add(edge);
}
}
return mst;
}
}
This implementation of Kruskal's algorithm first sorts the edges by their weights in descending order, then iterates through the edges and adds them to the minimum spanning tree if they do not create a cycle.
By understanding how to implement weighted edges and applying them in various graph algorithms, you can solve a wide range of problems in Java that involve weighted relationships between entities.