Determine Whether Matrix Can Be Obtained By Rotation — LeetCode 1886 Python Solution
- Problem
- #1886
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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
- 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.
Python solution
class Solution:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
def rotate(matrix):
n = len(matrix)
for i in range(n // 2):
for j in range(i, n - 1 - i):
t = matrix[i][j]
matrix[i][j] = matrix[n - j - 1][i]
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]
matrix[j][n - i - 1] = t
for _ in range(4):
if mat == target:
return True
rotate(mat)
return FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(m·n) |
| Space | O(1) to O(m·n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation?
- LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation is rated Easy on LeetCode.
- What topics does LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation cover?
- LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation is tagged Array and Matrix on LeetCode.