LeetCode 1886: Determine Whether Matrix Can Be Obtained By Rotation Solution
Master LeetCode problem 1886 (Determine Whether Matrix Can Be Obtained By Rotation), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To determine whether a matrix can be obtained by rotating another matrix, we can simulate the rotation operation and compare the rotated matrix with the target matrix. We will rotate the matrix by swapping elements in a cyclic manner layer by layer. If after any rotation the matrix matches the target matrix, we return true. Otherwise, we return false.
-
Algorithm:
- Check if mat and target are equal. If they are, return true.
- For each rotation, swap elements layer by layer until all layers are rotated.
- Compare the rotated matrix with the target matrix. If they match, return true.
- If no rotation matches the target matrix, return false.
-
Time Complexity: O(n^2) where n is the size of the matrix.
-
Space Complexity: O(1) as we are rotating the matrix in place.
:
Solution Code
class Solution {
public boolean findRotation(int[][] mat, int[][] target) {
if (Arrays.deepEquals(mat, target)) {
return true;
}
int n = mat.length;
for (int rotate = 1; rotate <= 4; rotate++) {
rotateMatrix(mat);
if (Arrays.deepEquals(mat, target)) {
return true;
}
}
return false;
}
private void rotateMatrix(int[][] mat) {
int n = mat.length;
for (int layer = 0; layer < n / 2; layer++) {
int first = layer;
int last = n - 1 - layer;
for (int i = first; i < last; i++) {
int offset = i - first;
int top = mat[first][i];
mat[first][i] = mat[last - offset][first];
mat[last - offset][first] = mat[last][last - offset];
mat[last][last - offset] = mat[i][last];
mat[i][last] = top;
}
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1886 (Determine Whether Matrix Can Be Obtained By Rotation)?
This page provides optimized solutions for LeetCode problem 1886 (Determine Whether Matrix Can Be Obtained By Rotation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1886 (Determine Whether Matrix Can Be Obtained By Rotation)?
The time complexity for LeetCode 1886 (Determine Whether Matrix Can Be Obtained By Rotation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1886 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1886 in Java, C++, or Python.