Problem
Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.
Example 1:

Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
Output: true
Explanation: We can rotate mat 90 degrees clockwise to make mat equal target.
Example 2:

Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
Output: false
Explanation: It is impossible to make mat equal to target by rotating mat.
Example 3:
.png)
Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]
Output: true
Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.
Constraints:
n == mat.length == target.lengthn == mat[i].length == target[i].length1 <= n <= 10mat[i][j]andtarget[i][j]are either0or1.
Concept
The problem utilizes the formula for n x n matrix rotation. This isn’t to be confused with rotation matrices in computer graphics.
The idea goes that to rotate a matrix, we need to shift the element at i, j to n-j-1, i where n is the number of rows of column. This formula only works on n x n matrices.
Formula
tempmatrix[n-j-1] = matrix[i][j]
Solution
There are only 3 possible rotations to check, as the 4th rotation is the matrix itself. So we rotate once and compare the rotated matrix with the target for match. If there s no match, try next rotation.
Algorithm
- Compare given matrix with target without any rotations.
- If matched, return true.
- else continue.
- Initialize a temporary matrix to store the rotated matrix.
- Repeat 3 times:
- Apply rotation.
- Compare rotated matrix to target.
- If matched, return true.
- else continue.
- Replace original matrix with rotated matrix.
- If none of the rotations match, return false.
Complexity
| Time | Space |
|---|---|
| O(n²) | O(n²) |
Implementation
bool compare(int** temp, int** target, int matSize) {
for (int i = 0; i < matSize; i++)
for (int j = 0; j < matSize; j++)
if (target[i][j] != temp[i][j])
return false;
return true;
}
void copy(int** temp, int** mat, int matSize) {
for (int i = 0; i < matSize; i++)
for (int j = 0; j < matSize; j++)
mat[i][j] = temp[i][j];
}
bool findRotation(int** mat, int matSize, int* matColSize, int** target, int targetSize, int* targetColSize) {
if (compare(mat, target, matSize))
return 1;
int** tempmat = (int**)malloc(matSize * sizeof(int*)); // Allocate rows
for (int i = 0; i < matSize; i++)
tempmat[i] = (int*)malloc(matSize * sizeof(int)); // Allocate columns
for (int i = 1; i <= 3; i++) {
for (int i = 0; i < matSize; i++)
for (int j = 0; j < matSize; j++)
tempmat[matSize - j - 1][i] = mat[i][j];
if (compare(tempmat, target, matSize))
return 1;
copy(tempmat, mat, matSize);
}
return 0;
}