Greedy Algorithms Questions Medium
Dijkstra's algorithm is a greedy algorithm that is used to find the shortest path in a weighted connected graph. It works by maintaining a set of vertices for which the shortest path has already been determined. Initially, the distance to all vertices except the source vertex is set to infinity.
The algorithm starts at the source vertex and iteratively selects the vertex with the minimum distance from the set of vertices not yet processed. This vertex is then added to the set of processed vertices.
For each selected vertex, the algorithm updates the distances of its neighboring vertices if a shorter path is found. This is done by comparing the current distance to the neighboring vertex with the sum of the distance to the selected vertex and the weight of the edge connecting them. If the sum is smaller, the distance is updated.
The process continues until all vertices have been processed or the destination vertex is reached. At the end of the algorithm, the shortest path from the source vertex to each vertex in the graph is determined.
To keep track of the shortest path, the algorithm also maintains a predecessor array that stores the previous vertex on the shortest path to each vertex. This allows us to reconstruct the shortest path from the source to any vertex by backtracking from the destination vertex to the source using the predecessor array.
Overall, Dijkstra's algorithm guarantees finding the shortest path in a weighted connected graph, provided that the graph does not contain negative weight edges. It has a time complexity of O(V^2) or O(E log V) depending on the implementation, where V is the number of vertices and E is the number of edges in the graph.