You can find the goal state by simply sorting the array. Let say you goal state is g
then a simple but inefficient algorithm to solve the puzzle would be:
void solve()
{
if(current_state == g)
return;
foreach(choice c in shifting_choices)
{
// shift neighbour
apply choice;
solve();
undo choice;
}
}
In above algorithm choices
are basically moving the blocks which are surrounded by the zeroth
block.
To improve the algorithm you can use A* (best first). In order to find best choice you can use Manhattan Distance
. It is basically steps required to reach one block to another within puzzle. Consider below:
6 2 1
5 0 3
4 7 8
In above situation, you could move 2, 5, 3, 7
but to find best move consider the goal state:
8 7 6
5 4 3
2 1 0
When you move a block to zeroth
block you are changing position of two blocks. Calculate sum of Manhattan Distance of these two blocks from their position within goal state. The choice within least sum will be most preferable:
Moving 2: 2 + 3 = 5
Moving 3: 1 + 1 = 2
Moving 7: 1 + 1 = 2
Moving 5: 1 + 2 = 3
You can break tie between 3 and 7 by checking their previous positions, 3 was at right place therefore 7 makes the locally most optimal choice.