1

I am tasked with programming an A* Search Algorithm for an assignment that involves solving an '8-Puzzle'.

One of the algorithm's steps is to:

Add all the extended paths to Q. If the descendant state is already in Q, keep only the shorter path to state in Q (where Q is a Priority Queue (PQ)).

As such, I will need to search the PQ if an identical state exists but has a shorter path. If an identical state already exists but it has a longer path, I will need to delete this state from the PQ.

I have been directed to use an STL PQ, not my own implementation. I have managed to implement other types of searches using the below to create a Min PQ - which works as desired.

auto cmp = [](Puzzle* a, Puzzle* b) { 
    return a->getHCost() > b->getHCost();
};


std::priority_queue<Puzzle*, std::vector<Puzzle*>, decltype(cmp)> Q(cmp);           

How can I extend my implementation so that...

  • I can perform a brute force search - looping through each element of the STL PQ?
  • I can delete an element somewhere in the STL PQ by its index? - shuffling elements 'upwards' if appropriate.
LJ__
  • 23
  • 3
  • Can't you simply have a secondary array shortest[] where shortest[i] is the shortest length found (yet) of a path to i? Then whenever you get in the top of the PQ an element with state x, you check shortest[x] if it is indeed the shortest found and do whatever you want to it, else delete the element from the top of the PQ. – JunisvaultCo Apr 08 '20 at 23:11
  • It is not possible search for elements in a `std::priority_queue` or delete elements other than the top one. You need a different data structure. – eesiraed Apr 09 '20 at 00:08

1 Answers1

0

You could have a secondary array named shortest[] where shortest[i] would be the shortest known path to the state i. Then whenever you get in the top of the PQ an element with state x, you check shortest[x] if it is indeed the shortest found and do whatever you want to it, else delete the element from the top of the PQ.

However, given that the states are from an 8-puzzle, you'd have to come up with an efficient way to give them a unique identifying number and ability to get it back efficiently. It is possible to do both such things in O(1). I'm not sure if I should spoil my personal idea yet, given it is after all an assignment and you should undertake such a challenge.

JunisvaultCo
  • 151
  • 7