The God Delusion
Time limit1sMemory limit128 MB
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 rows and columns there are atoms, numbered to . The atom in row and column (rows and columns are counted from ) has number .
The electrons are numbered to , and exactly one atom has no electron (shown as in the grid). Your goal is to move each electron onto the atom with the same number , leaving atom 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 and (, ). The next lines each contain integers giving the electron currently at that grid position; a 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
