class Solution {
public boolean solution(int[][] key, int[][] lock) {
for (int rotateCount = 0; rotateCount < 4; rotateCount++) {
if (rotateCount != 0) {
key = rotateTable90DegreeClockwise(key);
}
if (verifyKey(key, lock)) {
return true;
}
}
return false;
}
private int[][] rotateTable90DegreeClockwise(int[][] key) {
int size = key.length;
int[][] newKey = new int[size][size];
for (int r = 0; r < size; r++) {
for (int c = 0; c < size; c++) {
newKey[r][c] = key[size - 1 - c][r];
}
}
return newKey;
}
private boolean verifyKey(int[][] key, int[][] lock) {
int lockSize = lock.length;
int keySize = key.length;
int bigSize = lockSize + (keySize - 1);
for (int sR = 0; sR < bigSize; sR++) {
for (int sC = 0; sC < bigSize; sC++) {
int[][] newLock = moveKey(key, sR, sC, lockSize);
if (verify(lockSize, lock, newLock)) {
return true;
}
}
}
return false;
}
private int[][] moveKey(int[][] key, int sR, int sC, int lockSize) {
int keySize = key.length;
int bigSize = lockSize + (keySize - 1) * 2;
int[][] bigLock = new int[bigSize][bigSize];
int[][] rtLock = new int[lockSize][lockSize];
for (int r = sR, kR = 0; r < sR + keySize; r++, kR++) {
for (int c = sC, kC = 0; c < sC + keySize; c++, kC++) {
bigLock[r][c] = key[kR][kC];
}
}
for (int nR = keySize - 1, oR = 0; nR < (keySize - 1 + lockSize); nR++, oR++) {
for (int nC = keySize - 1, oC = 0; nC < keySize - 1 + lockSize; nC++, oC++) {
rtLock[oR][oC] = bigLock[nR][nC];
}
}
return rtLock;
}
private boolean verify(int lockSize, int[][] lock, int[][] newLock) {
for (int r = 0; r < lockSize; r++) {
for (int c = 0; c < lockSize; c++) {
if (lock[r][c] == newLock[r][c]) {
return false;
}
}
}
return true;
}
}