Refactored dijkstra's algorithm