I am implementing a priority queue based on heuristic for an 8 piece puzzle program. I am wondering how to easily do this. How would I go about pushing in the nodes and having the priority based on Heuristic instead of the strings.
struct node
{
string currentState; // Holds currentState of this node
int depth; // Depth of node in tree
int heuristic; // How many nodes are out of place
};
void Heuristic_Calc(node& puzzle) // Calculate Heuristic
{
// This function calculates the heuristic based on
// Out-of-Place tiles by comparing the current node
// to the Goal State and adding accordingly.
for (int i = 0; i < 9; i++)
{
if (puzzle.currentState[i] == goalState[i])
{
continue; // Compare to Goal
}
else
{
puzzle.heuristic++; // Cost Increase
}
}
}//end void Heuristic_Calc
void ASS(node puzzle) // A* Search w/ Heuristic
{
// Expand(temp, ASSFringe);
// This search algorithm will use cost based on
// out of place tiles (Heuristic).
clock_t t1, t2; // Timer Start
t1 = clock();
int check = 0; // Double Check for solution
counter = 0;
priority_queue <node> ASSFringe;
vector <node> container;
node temp;
Check_Map(puzzle);
ASSFringe.push(puzzle); // Initial Node
while (!ASSFringe.empty()) // Loop for Expansions
{
temp = ASSFringe.top(); // Copy node at front of queue
ASSFringe.pop(); // Pop node from queue
if (Check_Goal(temp) == 0) // Check Goal for return
{
// Goal found returns 0
cout << "Goal Found at <" << temp.depth << "> Depth." << endl;
cout << "Depth-First Search Complete!" << endl;
check++;
goto endASS;
}
else
{
// Goal not found returns 1
container.clear();
Expand(temp, container); // Expand for next node
for (int i = 0; i < container.size(); i++) // Transfer
{
ASSFringe.push(container[i]);
}
}
}
if (ASSFringe.empty()) // Empty Queue
{
if (check == 0) // Solution never found
{
cout << "Priority_Queue Empty! No Solution!" << endl;
}
}
endASS: // Branch if goal found
visited_states.clear(); // Clear Map after search ends
t2 = clock(); // Timer End
timer(t1, t2); // Run Time Calculator
}
Presumably you've implemented an operator< somewhere that makes this compile. Either have that operator return a value based on the heuristic, or supply a custom comparison function object to the priority_queue.
So, as this inserts nodes into the Fringe it will compare them with the other nodes and prioritize them as higher or lower based on the heuristic count.
I must be hitting an infinite loop somewhere in my code. Not sure, thank you for the info and help.