Welcome to ZOJ
64 - The 8th Zhejiang University Programming Contest - 1004
Dice Matrix

Time Limit: 10 Seconds      Memory Limit: 32768 KB

Dice Matrix is a puzzle made of several dice. The rules of this puzzle are as follows.

  1. Dice with six faces as shown in following figure are used in the puzzle.
  2. The direction of each die is also shown as in the following figure initially.
  3. The dice are arranged in n rows and m columns. The following figure shows a 3 * 3 dice matrix.
  4. Each time you can select a row or a column to rotate.
  5. You can rotate any angle you like.
  6. All the dice in that row/column must be rotated the same angle in the same direction.
  7. The dice can only be rotated perpendicular to the row/column. You can't rotate the dice along the row/column. (You can see the sample for more details.)
Given the target top faces of a dice matrix, your task is to find the minimum steps from the initial configuration to the target one.


Standard input will contain multiple test cases. The first line of the input is a single integer T (1 <= T <= 2000) which is the number of test cases. And it will be followed by T consecutive test cases.

The first line of each test case contains two integers n and m (1 <= n, m <=4, n * m <= 10), indicating the number of rows and the number of columns of the dice matrix. The next n lines will contain m integers separated by one space each, which are between 1 and 6 inclusive, indicating the target top faces of the dice matrix.


If you can make it to the target result in 5 steps, print the number of minimum steps in one line; otherwise print the word "Impossible" on a single line.

Sample Input

2 2
2 1
2 1
2 2
6 1
6 1
1 2
2 2
1 1
2 2
1 3
2 4

Sample Output


In the first sample, you can get the result by rotating the first column by 90 degrees clockwise.
In the second sample, you can get the result by rotating the first column by 180 degrees clockwise.
In the third sample, you can not select the first row and rotate each dice along the row. You can only rotate each column separated.
In the fourth sample, no rotation is needed.

Submit    Status