Leetcode 1886. Determine Whether Matrix Can Be Obtained By Rotation
Leetcode Problem 1886: Determine Whether Matrix Can Be Obtained By Rotation
Given two n x n binary matrices mat
and target
, return true
if it is possible to obtain target
by rotating mat
in 90-degree increments, otherwise return false
.
public class Solution {
public boolean findRotation(int[][] mat, int[][] target) {
int n = mat.length;
for (int i = 0; i < 4; i++) { // Checking for 0, 90, 180, and 270 degrees rotations
if (areMatricesEqual(mat, target)) {
return true;
}
mat = rotate90(mat);
}
return false;
}
private boolean areMatricesEqual(int[][] mat1, int[][] mat2) {
int n = mat1.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (mat1[i][j] != mat2[i][j]) {
return false;
}
}
}
return true;
}
private int[][] rotate90(int[][] mat) {
int n = mat.length;
int[][] rotated = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
rotated[j][n - 1 - i] = mat[i][j];
}
}
return rotated;
}
}
This solution efficiently handles the requirements and constraints given, ensuring correctness while maintaining readability.
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?