Solve the 8 Puzzle

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.

st0le

Posted 2011-03-09T06:51:34.713

Reputation: 2 002

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-9 be grid 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

Answers

4

Python, 418 characters

The code exhaustively enumerates all positions and makes maps of their depth (D), and a position one closer to solved (E). Then it looks up the goal state to get the output.

D={(1,2,3,4,5,6,7,8,0):0}
E=D.copy()
def Z(a,d):
 b=list(a);b[i],b[i+d]=b[i+d],0;b=tuple(b)
 if b not in E:E[b]=a;D[b]=D[a]+1
for x in' '*32:
 for a in E.copy():
  i=list(a).index(0)
  if i>2:Z(a,-3)
  if i%3:Z(a,-1)
  if i%3<2:Z(a,1)
  if i<6:Z(a,3)
g=[]
for x in' '*3:g+=map(int,raw_input().split())
g=tuple(g)
if g in E:
 print D[g]
 while g:
  for i in(0,3,6):print'%d %d %d'%g[i:i+3]
  g=E[g];print
else:print -1

Keith Randall

Posted 2011-03-09T06:51:34.713

Reputation: 19 865

like the ' '*3 trick. – st0le – 2011-03-10T04:47:14.473