Determine Whether Matrix Can Be Obtained By Rotation

To solve this problem, we can simulate the process of rotating the matrix. To rotate a matrix 90 degrees clockwise, we can first transpose the matrix and then reverse each row. We repeat this process four times (since a full rotation is 360 degrees) and after each rotation, check if the rotated matrix is equal to the target matrix.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
        def rotate(matrix):
            # Transpose the matrix
            for i in range(len(matrix)):
                for j in range(i, len(matrix[0])):
                    matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

            # Reverse each row
            for i in range(len(matrix)):
                matrix[i] = matrix[i][::-1]

        # Try rotating the matrix four times
        for _ in range(4):
            if mat == target:
                return True
            rotate(mat)

        return False

In the rotate function, we first transpose the matrix by swapping the elements on the diagonal and then reverse each row to get the matrix rotated 90 degrees clockwise. In the main function, we try to rotate the matrix four times and after each rotation, we check if the rotated matrix is equal to the target matrix. If it is, we return True. If after four rotations the matrix is not equal to the target matrix, we return False.