Manhattan Wiring
Time limit1sMemory limit128 MB
Find two vertex-disjoint shortest simple paths on a small grid connecting two pairs of marked cells while avoiding obstacles, minimizing total path length or returning 0 if impossible.
- Level
Hard8 of 10
- Topics
- Graph, BFS, Brute force
- Solved
- No attempts yet
Problem
You are given a rectangular grid of cells. Exactly two cells are marked "2" and exactly two other cells are marked "3"; some cells are obstacles.
Connect the two "2" cells with one line, and the two "3" cells with another line. A line runs through the centers of non-obstacle cells, moving only horizontally or vertically between orthogonally adjacent cells.
The rules are:
- A line may not pass through an obstacle cell.
- Each cell may be used by at most one line. Hence the two lines never share a cell and never cross.
- The length of a line is the number of cell borders it crosses; a line joining two adjacent cells has length .
Make the sum of the two line lengths as small as possible and output that minimum. If the two pairs cannot both be connected under these rules, the answer is .
For example, in the first grid of the first sample below, both pairs can be connected with a minimum total line length of .
Input
The first line contains the number of data sets .
The first line of each data set contains the number of rows and the number of columns . (, )
The next lines describe the grid from the top row to the bottom row; each line contains integers separated by spaces. The meaning of each integer is:
- : empty cell
- : obstacle
- : a cell marked "2"
- : a cell marked "3"
Every grid contains exactly two cells marked "2" and exactly two cells marked "3".
Output
For each data set, print on its own line the minimum possible sum of the two line lengths. Print if the two pairs cannot both be connected.