1

I'm working on implementing a Best-First Search algorithm to solve an 8-Puzzle problem for an assignment. Based on the requirements, it must be implemented using a (min) Priority Queue or Heap located in the Standard Template Library (STL).

I understand that it would be useful to use either data structure to organise expanded puzzle states by best heuristic cost (ie. the smallest cost).


Beginning with a 3x3 matrix (implemented using an array)

Puzzle *current=new Puzzle(initialState, goalState);

Each new puzzle state (an object) is created using:

Puzzle *next=(current->moveDown());
Puzzle *next=(current->moveRight());
Puzzle *next=(current->moveUp());
Puzzle *next=(current->moveRight());

I'd like to .push(next) onto a (Min) Priority Queue or Heap (of Puzzle*), sorted according to next->FCost.


Generically, is there a way that I can use either of these STL data structures to contain pointers to objects - sorted by a member variable (FCost) specific to each object?

LJ__
  • 23
  • 3
  • You can use a custom ordering function with `priority_queue`. (You can do that with all ordered collections.) – molbdnilo Mar 31 '20 at 07:20
  • Unrelated, but I don't see why current needs to be allocated dynamically. See [Resource Acquisition Is Initialization (or better named, end-scope does cleanup)](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e6-use-raii-to-prevent-leaks). I'd recommend simply `Puzzle current(initial, goal)`. Notwithstanding of course your other variables may point into that stack variable, e.g. `Puzzle *next = current.moveDown();` – TamaMcGlinn Mar 31 '20 at 08:51
  • The rule of thumb is, don't ever write `new` without wrapping it immediately into a resource-handling class, such as `std::unique_pointer current = std::make_unique(new Puzzle(initial, goal));`. – TamaMcGlinn Mar 31 '20 at 08:53

1 Answers1

0

Yes, you can specify a custom compare function for priority_queue

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

std::priority_queue<Puzzle*, std::vector<Puzzle*>, decltype(cmp)> queue(cmp);
sparik
  • 1,181
  • 9
  • 16