Sorting the puzzle

Consider a puzzle consisting of a board n×mn \times m, where all the squares except one have a different number between 1 and n*m1n*m - 1. The only allowed movement consists of moving an adjacent number (horizontally or vertically) to the empty square, it makes that the empty square “moves” where the number was. The aim is to leave the puzzle sorted from top to bottom and from left to right, with the empty square at the bottom on the left.

Write a program that prints if a given puzzle has solution or not. If it has, your program must print which is the minimal number of steps to solve it.

Input

Input consists of two natural numbers strictly positive (and small) nn and mm, followed by nn rows with mm natural numbers each one. Each number between 0 and n*m1n*m - 1 appears exactly once; the zero indicates the square initially empty.

Output

Your program must print the minimal number of steps to solve the puzzle, following the format of the instances. If there is not any possible solution, it must print "no solution".

Problem information

Author: Unknown
Translator: Carlos Molina

Generation: 2026-01-25T10:30:46.323Z

© Jutge.org, 2006–2026.
https://jutge.org