Server Time: Wed Sep 23, 2020 6:48 am
Welcome ( logout
I - Rider
PDF (English) Ranklist
Time Limit: 1 second(s) Memory Limit: 32 MB

A rider is a fantasy chess piece that can jump like a knight several times in a single move. A rider that can perform a maximum of K jumps during a single move is denoted as a K-rider. For example, a 2-rider can jump once or twice during a single move, and a 1-rider is a traditional knight.

There are some riders of different types on a chessboard. You are given a 2D board representing the layout of the pieces. The jth character of the ith element of board is the content of the square at row i, column j. If the character is a digit K between '1' and '9', the square contains a K-rider. Otherwise, if the character is a '.', the square is empty. Find the minimal total number of moves necessary to move all the riders to the same square. Only one piece can move during each move. Multiple riders can share the same squares all times during the process. Print -1 if it is impossible.

A traditional knight has up to 8 moves from a square with coordinates (x, y) to squares (x+1, y+2), (x+1, y-2), (x+2, y+1), (x+2, y-1), (x-1, y+2), (x-1, y-2), (x-2, y+1), (x-2, y-1), and can't move outside the chessboard.


Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case begins with a blank line and two integers m, n (1 ≤ m, n ≤ 10) denoting the rows and the columns of the board respectively. Each of the next m lines will contain n integers each denoting the board.


For each case of input you have to print the case number the desired result.

Sample Input

Output for Sample Input



3 2





3 3





10 10












1 4


Case 1: 0

Case 2: 4

Case 3: 14

Case 4: -1


Developed and Maintained by
Copyright © 2012
LightOJ, Jane Alam Jan