I've read many similar articles, I apologise if this has already been answered, but I'm still stuck.
I'm coding a function to populate a tree, each node having four branches, which will store the possible manipulation of states of the "eight tile puzzle" i.e. http://www.8puzzle.com/images/8_puzzle_start_state_a.png
The problem is I've reached, what I believe to be, stack overflow, due to the heavily recursive nature of the problem at hand.
Tail recursion seems like the solution, though I'm not sure if it is relevant/possible or how to implement it in this instance. Code follows:
void Tree::insert(string &initialState, const string &goalState, tree_node *&inNode){
cout<<"insert called"<<endl;
depth++;
cout<<depth<<endl;
string modState;
int zeroPos=0;
if(initialState==goalState){
cout<<"* * * GOAL * * *"<<endl;
getchar();
exit(0);
}
if(inNode==NULL){//is this the first node?
inNode = new tree_node(initialState);
root=inNode;
inNode->parent=NULL;
insert(initialState, goalState, inNode);
}else{
inNode->state = initialState;
for(zeroPos=0;zeroPos<initialState.size();zeroPos++){//where is the empty tile?
if(initialState[zeroPos]=='0'){
break;
}
}
//left
if(zeroPos!=0 && zeroPos!=3 && zeroPos!=6){//can the empty tile move left?
modState=initialState;
modState[zeroPos]=modState[zeroPos-1];
modState[zeroPos-1]='0';
if(isOriginal(modState, inNode) ){//does this state already exist?
cout <<"left " << modState[0]<<modState[1]<<modState[2]<<endl;
cout <<"left " << modState[3]<<modState[4]<<modState[5]<<endl;
cout <<"left " << modState[6]<<modState[7]<<modState[8]<<endl;
inNode->l = new tree_node(modState);
inNode->l->parent= inNode;
if(inNode->l != NULL){
insert(modState, goalState, inNode->l);
}
}
}
}
}
}