Implements Dijkstra's algorithm