6789
InterviewTime limit1sMemory limit1024 MB
Each cell holds a card 6, 7, 8, or 9; turning a card rotates it (6 and 9 swap, 8 and 7 stay). Find the minimum number of turns so the grid stays the same after a 180-degree rotation, or -1 if impossible.
- Level
Medium4 of 10
- Topics
- Implementation, Greedy, Matrix
- Solved
- No attempts yet
Problem
Jaehyun likes digits. Among the 10 digits, he likes 6, 7, 8, and 9 the most. So he made a special card set consisting only of 6, 7, 8, and 9.
Jaehyun currently has cards. He wants to make a magical by card matrix. Each row of the matrix must contain cards. He has already arranged his cards in the shape of an by matrix.
\
Figure 1. Initial state, not point symmetric.
To be a magic matrix, the matrix must be point symmetric. Rotating the matrix 180 degrees must give the original matrix. For example, 8 is point symmetric with itself, and 6 and 9 are point symmetric with each other.
Jaehyun does not want to change the positions of the cards, so his goal is to make the matrix point symmetric by only rotating cards in their original positions.

Figure 2. After rotating two cards, they are point symmetric.
Find the minimum number of cards you have to turn to make a magic matrix.
Input
The first line contains two integers, and . ()
Each of the next lines contains a string of characters which denotes the numbers written in each card. It is guaranteed that each character is one of 6, 7, 8, or 9.
Output
Print the minimum number of cards you have to turn to make a magic matrix in the first line. If it is not possible to make a magic matrix, print "-1". (without quotes)