Admiral
Time limit1sMemory limit512 MB
Find the fewest swaps of the flagship (0) with an adjacent battleship needed to place every kind in its own row, or report that more than 20 swaps are required.
- Level
Medium6 of 10
- Topics
- Graph, BFS, Simulation
- Solved
- No attempts yet
Problem

You are the admiral of a naval troop with 21 battleships in 6 kinds. There is one flagship, denoted 0, and the admiral must be on it. Kinds 1 to 5 have 2, 3, 4, 5, and 6 ships, respectively.
The battlefield has 6 rows, and all battleships have the same rectangular shape. In the optimal arrangement, every battleship of kind is in row (rows are numbered from 0).
The initial state occupies the 21 required positions, but some ships may be in the wrong row. You can swap the flagship with an adjacent battleship. Two battleships are adjacent if they are not in the same row and share part of an edge. For example, cell is adjacent to , , , and , where is the cell in row and position from the left (both numbered from 0).
Find the minimum number of swaps needed to reach the optimal arrangement, or report that more than 20 swaps are required.
Input
The first line contains an integer , the number of test cases ().
Each test case consists of 6 lines. The -th line contains space-separated integers, the kinds of battleships in row from left to right.
Output
For each test case, print too difficult on a single line if the goal cannot be reached in 20 or fewer swaps. Otherwise, print the minimum number of swaps on a single line.