12
2
The 8 Puzzle is the smaller variant of the 15Puzzle (or the Sliding puzzle).
You have a 3x3 grid which is filled with numbers from 0-8 (0 denotes the blank tile) arranged in a random order.
Your task is to input a 3x3 grid and show the shortest solution (minimum moves) to get to the goal state. Display each boardstate including the first state in the output.
There may be multiple optimal solutions, you just need to print one.
Input: (small example)
1 2 0
4 5 3
7 8 6
Output:
2 <- denotes minimum number of moves required
1 2 0
4 5 3
7 8 6
1 2 3
4 5 0
7 8 6
1 2 3
4 5 6
7 8 0 <- goal state
If the puzzle can't be solved, print just -1 (denoting unsolvable)
Edit: Time limit : < 30seconds.
For those not familiar with the npuzzle, please read the link provided... – st0le – 2011-03-09T07:02:13.497
in your question , shouldn't
grid which is filled with numbers from 0-9begrid which is filled with numbers from 0-8? – Clyde Lobo – 2011-03-09T09:07:58.707@Clyde, Oops! :) Fixed. – st0le – 2011-03-09T10:14:58.670
Pretty sure it's always possible to solve, right? – Magic Octopus Urn – 2017-08-01T13:50:56.207
@MagicOctopusUrn If you arrived at the initial state from the Goal state using the sliding rules, it's always solvable. If you arbitrarily put in tiles then there are states that cannot be solved. Google for Solvability for n puzzle – st0le – 2017-08-01T19:38:07.810
@st0le Yeah, you're right. I remember now. I was using my old slide toy as a reference and that does make sense. – Magic Octopus Urn – 2017-08-01T19:41:17.207