Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for 8 Puzzle by Tinus_Trotyl
'''
8 puzzle (3x3)
Solve the puzzle:
U - up
D - down
L - left
R - right
'''
Moves = {'U': (0, -1), 'D': (0, 1), 'L': (-1, 0) , 'R': (1, 0)}
def lookup (a) : # lookup pos. of [a]
for y, row in enumerate(puzzle):
if a in row:
x = row.index(a)
break
return x,y
def move (mvs) : # move it
global solution
if mvs :
for m in mvs :
x, y = lookup(0)
swap_x, swap_y = x + Moves[m][0], y + Moves[m][1]
if 0 <= swap_x < 3 and 0 <= swap_y < 3:
puzzle[y][x], puzzle[swap_y][swap_x] = puzzle[swap_y][swap_x], 0
else : ERROR
solution = solution + mvs # and keep record of moves
def checkio (p) :
global puzzle, solution
puzzle, solution = p, ""
x, y = lookup(0) # [open space] --> (1, 1)
move((2-x) * "R" + (2-y) * "D" + "UL")
x, y = lookup(1) # [1] --> (0, 0)
if x == 0 : move(y * "ULDDRU")
if x == 1 : move((y//2) * "DLUURD" + "LURD")
if x == 2 : move(y * "URDDLU" + 2 * "LURRDL")
x,y = lookup(2) # [2] --> (2, 0)
if x == 2 and y == 0 : pass
else :
if x == 1 and y == 0 : move("RULD")
else :
while lookup(2) != (2, 1) :
move("LDRRUL")
move("URDL")
if lookup(3) == (1, 0) : # [3] --> (2, 1)
move("RULDRDLLURURDLLDRRUULDRULD")
while lookup(3) != (2, 1) :
move("LDRRUL")
move("URDL") # [2] & [3] --> resp. (1, 0) & (2, 0)
while lookup(4) != (0, 1) : # [4] --> (0, 1)
move("LDRRUL")
if lookup(5) == (0, 2) : # and finish it by [5] & [6]
while lookup(6) != (2, 1) :
move("DRUL")
move("DLURDRULLDRURD")
if lookup(6) == (0, 2) :
while lookup(5) != (2, 1) :
move ("DRUL")
move("RDLLURDRULLDRR")
if lookup(5) == (2, 1) and lookup(6) == (1, 2) : move("DRUL")
if lookup(5) == (2, 2) and lookup(6) == (1, 2) : move("RDLU")
if lookup(5) == (1, 2) and lookup(6) == (2, 2) : move("DLURRDLULDRR")
if lookup(5) == (2, 2) and lookup(6) == (2, 1) : move("RDLURDLLURRDLULDRR")
if lookup(5) == (2, 1) and lookup(6) == (2, 2) : move("RD")
if lookup(5) == (1, 2) and lookup(6) == (2, 1) : move("DR")
return solution
May 19, 2017