LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1886. Determine Whether Matrix Can Be Obtained By Rotation

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.length
  • n == mat[i].length == target[i].length
  • 1 <= n <= 10
  • mat[i][j] and target[i][j] are either 0 or 1.

Solutions

Solution 1: In-Place Comparison

We observe the rotation pattern of the matrix and find that for an element mat[i][j], after rotating 90 degrees it appears at position mat[j][n-1-i], after rotating 180 degrees it appears at position mat[n-1-i][n-1-j], and after rotating 270 degrees it appears at position mat[n-1-j][i].

Therefore, we can use an integer ok to record the current rotation state, initialized to 0b1111, indicating that all four rotation states are possible. For each element in the matrix, we compare whether its position under different rotation states matches the corresponding element in the target matrix. If they are not equal, we remove that rotation state from ok. Finally, if ok is not zero, it means at least one rotation state can make the matrix consistent with the target matrix, and we return true; otherwise, we return false.

The time complexity is O(n2), where n is the size of the matrix. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustC#Kotlin
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !