0

I am trying to write an algorithm that operates on a grid. It is similar to Dijkstra's algorithm, but slightly different.

Each point in the grid is either occupied or free. I want to examine ALL of the reachable points that are less than a certain distance away from a starting point.

I am assuming that I can travel parallel to the grid lines or diagonally at a cost of 1 and sqrt(2), respectively.

The easiest way to do this would be if I had a map that was sorted by value. This way I could set the key to be the co-ordinates of each point, and the value to be the so-far calculated distance to the point. I would just have to pop the entry with the smallest distance and then find and update the so-far distance of the neighbors points.

Such a container doesn't exist, so I've been thinking about which containers I could combine in order to give me the same behavior, but I am having trouble coming up with anything that works.

I was thinking that I could have an unordered_set or unordered_map which allow for fast retrievable of so-far distances for each point. For the unordered_set I could defined a gridNode object which contains both location and so-far distance of the point.

Then, I could have a vector that I would sort and use to find the shortest distance.

I am just not sure how to keep these two containers consistent. Would the vector contain pointers to the entries in the unordered_set? Could the vector contain the co-ordinates of the grid points and I could write std::sort so that it uses the unordered_map to sort correctly?

Any thoughts on this would be appreciated.

user2445507
  • 443
  • 3
  • 13
  • http://stackoverflow.com/questions/5493474/graph-implementation-c has an overview of data structures for storing graphs in C++. Any would be easy to generate for a regular grid. – stark Jul 30 '15 at 21:00

1 Answers1

0

When dealing with Dijkstra and Dijkstra-like algorithms, priority queues are your friend. Standard C++ provides one implementation with std::priority_queue. You’ll have to store pairs of the coordinates and the distance and define a custom comparator that only compares the values of pairs.

Robin Krahl
  • 5,268
  • 19
  • 32
  • If I wanted to use a priority queue, wouldn't I need to be able to change the priorities after insertion? I thought priority_queue doesn't allow this. – user2445507 Jul 30 '15 at 21:11
  • @user2445507 no, just insert the coordinate a second time. As the distance of the new entry is shorter, it will appear before the old entry. The older entry with a longer distance will either never show up or at least won’t lead to a shorter way. (You’ll have to store a list of nodes that have been visited/settled anyway.) – Robin Krahl Jul 30 '15 at 21:23