You are given two n x n binary matrices mat and target. You are allowed to rotate mat 90 degrees clockwise any number of times. Return true if it is possible to make mat equal to target, 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 to target.
Example 2:
Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
Output: false
Explanation: It is impossible to rotate mat to make it equal to target.
target matrix.target matrix.target matrix, return true. If none match, return false.def rotate_90(mat):
n = len(mat)
rotated = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
rotated[j][n - i - 1] = mat[i][j]
return rotated
def findRotation(mat, target):
# We will rotate mat 4 times (0, 90, 180, 270 degrees)
for _ in range(4):
if mat == target:
return True
mat = rotate_90(mat)
return False
# Example usage
mat = [[0,1],[1,0]]
target = [[1,0],[0,1]]
print(findRotation(mat, target)) # Output: True
mat = [[0,1],[1,1]]
target = [[1,0],[0,1]]
print(findRotation(mat, target)) # Output: False
O(n^2) since we need to rearrange elements in an n x n matrix.O(n^2).Since we perform up to 4 rotations and compare each resulting matrix:
O(4 * n^2), which simplifies to O(n^2).This solution is efficient for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?