Uniform Cost Search | Shortest Path in a Weighted Graph

In Dijkstra's algorithm, we add all vertices to the priority queue at the beginning. However, this is not possible when we have a large graph that does not fit in memory, or even infinite graph. The Uniform Cost Search algorithm is a variant of Dijkstra's algorithm. We start with the priority queue containing only the root node, and add new vertices as we checking the neighbours.

An optimization is to terminate the search as soon as you reach a destination node. This is if you are finding the distance only between 2 nodes. If this is the case you can terminate the search early and exit the loop as soon as you reach the destination node.