spoj#DCEPC706. Meeting For Party
Meeting For Party
Ankur, Anuja and Jyoti are planning to have party at some place. Their houses are located at different points in a rectangular grid of size M*N. They want to meet in minimum time and then party.
The M rows and N columns rectangular grid contains some impassable points (denoted by a #), however. So none of them wants to step over these points. They can only step over passable points (denoted by a .). They can also meet at some point outside the grid. You can assume that the points outside the grid are all passable. They cannot party on an impassable point and they have their house only on passable point. They can move either to North, South, East or West passable point from the current passable point and it takes 1 unit time to do so. Also they can wait at a passable point if they want to.
Find the minimum time of meeting.
Note: Assume that they will always meet at some point.
Input
First line gives T, the no. of test cases.
Each test case has two space separated integers M and N, the dimensions of the grid.
Next M lines contain N characters per line (no spaces). Characters can be either “#” (impassable) or “.” (passable) or “1” (Ankur’s house) or “2” (Anuja’s House) or “3” (Jyoti’s house). Each test case will have exactly 1 “1”, exactly 1 “2” and exactly 1 “3”.
Output
Output T lines, each containing the required answer.
Constraints
1<=T<=10
1<=M<=200
1<=N<=200
Example
Input:4 41#...4 4 #... .2#. ..#3 1..#.2#...#31..#Output: 4