Description
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:
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.
Solutions
This function determines whether a target matrix is a rotated version of the input matrix by checking all four possible rotations (0°, 90°, 180°, and 270°). It maintains four boolean flags—rot0, rot90, rot180, and rot270—and iterates through every position [r, c] in the matrix, comparing elements from the source matrix at rotation-adjusted coordinates to the corresponding position in the target. For each rotation, it uses the formula mat[adjusted_row][adjusted_col] === target[r][c] to verify if that rotation produces the target; for example, a 90° rotation reads from mat[c][n-1-r], while a 180° rotation reads from mat[n-1-r][n-1-c]. If all four rotations are ruled out at any point (all flags become false), the function returns early for efficiency. Finally, it returns true if any of the four rotations produced a match with the target matrix.
/**
* @param {number[][]} mat
* @param {number[][]} target
* @return {boolean}
*/
var findRotation = function(mat, target) {
const n = mat.length;
let rot0 = true;
let rot90 = true;
let rot180 = true;
let rot270 = true;
for (let r = 0; r < n; r++) {
for (let c = 0; c < n; c++) {
const inv_r = n - 1 - r;
const inv_c = n - 1 - c;
rot0 &= mat[r][c] === target[r][c];
rot90 &= mat[c][inv_r] === target[r][c];
rot180 &= mat[inv_r][inv_c] === target[r][c];
rot270 &= mat[inv_c][r] === target[r][c];
if (!rot0 && !rot90 && !rot180 && !rot270) {
return false;
}
}
}
return rot0 || rot90 || rot180 || rot270;
};