This page is still under construction.

Parts of this page are still being built. What you see may change.

The God Delusion

Time limit1sMemory limit128 MB

Summary
On a tiny grid each atom holds one numbered electron except a blank; slide electrons into empty neighbours to send each to its own atom in the fewest moves.
Level

Medium7 of 10

Topics
BFS, Graph, Shortest path, Simulation
Solved
No attempts yet

Problem

You are God, building the universe. While arranging the silicon crystals you run into a problem: aluminium impurities have stolen the silicon atoms' electrons, and the crystals are demanding their electrons back. Luckily you caught it early, so the crystals are still small. Even a god has little time to spare, so you must return every electron to its proper atom in the fewest possible moves.

There is only one way to move an electron: take an electron from an atom and slide it into a neighbouring atom that currently has none. One move is one such slide.

Model the crystal lattice as a planar rectangular grid in which every atom is connected to its four neighbours (up, down, left, right). For a grid of hh rows and ww columns there are n=h×wn = h \times w atoms, numbered 00 to n−1n-1. The atom in row ii and column jj (rows and columns are counted from 00) has number i×w+ji \times w + j.

The electrons are numbered 11 to n−1n-1, and exactly one atom has no electron (shown as 00 in the grid). Your goal is to move each electron kk onto the atom with the same number kk, leaving atom 00 without an electron. Find the minimum number of moves needed.

Input

The input consists of several test cases. The first line of each test case contains two integers hh and ww (2≤h,w≤52 \le h, w \le 5, h×w≤10h \times w \le 10). The next hh lines each contain ww integers giving the electron currently at that grid position; a 00 marks the atom with no electron.

A line containing only 0 0 ends the input.

Output

For each test case, print on one line the minimum number of moves required to return every electron to the atom with its own number.

Hint

Examples2

  1. Example 1

    Input
    2 2
    1 0
    2 3
    2 3
    1 2 5
    3 4 0
    0 0
    
    Expected output
    1
    3
    
  2. Example 2

    Input
    2 2
    0 1
    2 3
    0 0
    
    Expected output
    0