712228. Shortest Path in Weighted undirected graph
Here is the detailed Markdown blog post for the GeeksforGeeks problem "Shortest Path in Weighted undirected graph":
Shortest Path in Weighted undirected graph
Summary
The goal is to find the shortest path between two nodes in a weighted, undirected graph. This involves traversing the graph and calculating the minimum total weight of the path from one node to another.
Detailed Explanation
The problem can be solved using Dijkstra's algorithm, which is an efficient method for finding the shortest paths among nodes in a graph. The algorithm works by maintaining a priority queue where the priority of each node is its distance from the starting node.
Here's a step-by-step breakdown of the solution:
- Initialize the distance to the starting node as 0 and all other nodes as infinity.
- Create a priority queue and insert the starting node with a distance of 0.
- While the priority queue is not empty, extract the node with the minimum distance (i.e., the closest node to the starting node).
- For each neighbor of the extracted node that has not been visited yet:
- Calculate the total weight of the path from the starting node to this neighbor through the extracted node.
- If this calculated weight is less than the current distance to this neighbor, update the distance and mark the neighbor as visited.
- Repeat steps 3-4 until the destination node has been processed.
Time Complexity: O((E + V) log E), where E is the number of edges and V is the number of vertices.
Space Complexity: O(V), for storing the distances and visited status of each vertex.
Here's an ASCII art diagram to illustrate the algorithm:
+---------------+
| Starting Node |
+---------------+
|
|
v
+---------------+
| Neighboring |
| Nodes (with |
| distances) |
+---------------+
^ ^
| |
| Priority|
| Queue |
v v
+---------------+
| Extracted Node|
| (minimum |
| distance) |
+---------------+
Optimized Solutions
Java
import java.util.*;
public class ShortestPath {
public static int shortestPath(int[][] graph, int start, int end) {
int[] dist = new int[graph.length];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(start);
while (!pq.isEmpty()) {
int node = pq.poll();
for (int neighbor : graph[node]) {
if (neighbor == end) {
return dist[node] + 1;
}
if (dist[neighbor] > dist[node] + 1) {
dist[neighbor] = dist[node] + 1;
pq.offer(neighbor);
}
}
}
return -1; // No path found
}
}