Determine Whether Matrix Can Be Obtained By Rotation Problem
#1886
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1886.
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.
Solution
Approach: Compare All Four Rotations
Target cell target[i][j] must equal mat[j][n-1-i] for a 90 degree rotation, mat[n-1-i][n-1-j] for 180 and mat[n-1-j][i] for 270 (and mat[i][j] for no rotation). Instead of building rotated matrices, keep a 4-bit mask of rotations that still match target, and clear a bit whenever one of the four mapped cells differs. If the mask becomes 0 return false; if the scan finishes with a non-zero mask return true.
Complexity: O(n^2) time, O(1) space.
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
n = len(mat)
ok = 0b1111
for i in range(n):
for j in range(n):
if mat[i][j] != target[i][j]:
ok &= ~0b0001
if mat[j][n - 1 - i] != target[i][j]:
ok &= ~0b0010
if mat[n - 1 - i][n - 1 - j] != target[i][j]:
ok &= ~0b0100
if mat[n - 1 - j][i] != target[i][j]:
ok &= ~0b1000
if ok == 0:
return False
return ok != 0