简体   繁体   中英

Finding shortest path between nodes using Dijkstra's and min heap c++

This is more of a general question. I have a map that maps the name of a city to its node(containing basic info such as country, lat, long, etc.). Each city node has an array of edges pointing to destination nodes. The edge has a time and a cost member. I would like to find the shortest time to travel between two nodes, but I've begun confusing myself about the best way to go about this.

I have created my own min heap class that is based on a vector of city nodes. I am able to create the map add the city nodes from the map to the min heap. I have written the dijkstra's algorithm to find the shortest path and it works for some paths but not all. I believe this is because when I update the weight of a city node for dijkstra's algorithm, the heap is not being sorted correctly.

Once I update the weight of a node, how am I supposed to re-heapify the heap so that the lowest weight is at the top?

Thank you!

If you want to sort the entire heap then have a quick look at http://en.wikipedia.org/wiki/Heapsort

There's some pseudocode on there to help out and you might need to rearrange it to get the lowest at the top but that should work out for you. Otherwise, you can have a look at up heap bubbling and apply that at each stage rather than completely reorganizing the heap.

http://en.wikipedia.org/wiki/Binary_heap

They're a bit complex to describe here but up/down heap bubbling will ensure that your heap is organised correctly. It's also worth noting that a heapsort will run at O(n log n) for the worst case, while bubbling is O(log n) for most operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM