Reputation: 644
I'm trying to code a puzzle solver app. I need to find out how many moves it takes, and how many solutions there are.
I would rather not give too many details on the puzzle. but the player moves around a grid ( say 5 x 7 ) as they move, obstacles could be captured so the state of the board needs to be tracked. ( this could be done as a string or an array )
I understand I need to create a TreeNode, starting with a root ( the players start position ) and give each node children of the possible moves until all the possible moves are calculated. The puzzle stats could then be collected. Number of Possible solutions, minimum number of moves to solve, average number of moves to solve, etc.
I have the puzzle logic created that will return if moves are possible and such. I'm having problems creating the TreeNode structure and making sure moves are not duplicated.
The puzzle app itself is on the iPhone, but I'm writing this solver/editor on the Mac. Any help would be VERY much appreciated.
Upvotes: 3
Views: 434
Reputation: 240
For detecting repeated states, you would put the states in a set as you went along, and then check every time you found new states to see if they already existed. Though if space is an issue, you will have to resort to only checking if the children are not the same as the parent, or some kind of limited version of this approach.
A node class is very simple. It just contains a pointer back to a parent (if it has one) and the variable it holds (such as a state). You will also probably want other variables depending on your application.
When you get to a node, you use a successor function to get all the child nodes from there (the states that can be reached in one move) and add them to a list. You pluck from the list to traverse the tree.
Upvotes: 1
Reputation: 1438
Perhaps you could do a variant of a tree recursion? Traverse the tree recursively, having each end node return a value of how hard it was to get there (if there are costs associated with different moves) and a description of how it got there. This of course requires the player to only move in one direction, otherwise the tree-structure doesn't describe the problem. A bit more info on what your exact problem looks like would be helpful.
It might be a heavy algorithm, but it gets the job done.
Upvotes: 1