Skip to content

1886. Determine Whether Matrix Can Be Obtained By Rotation 👍

  • Time: $O(n^2)$
  • Space: $O(n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) {
    for (int i = 0; i < 4; ++i) {
      if (mat == target)
        return true;
      rotate(mat);
    }
    return false;
  }

 private:
  void rotate(vector<vector<int>>& mat) {
    ranges::reverse(mat);
    for (int i = 0; i < mat.size(); ++i)
      for (int j = i + 1; j < mat.size(); ++j)
        swap(mat[i][j], mat[j][i]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public boolean findRotation(int[][] mat, int[][] target) {
    for (int i = 0; i < 4; ++i) {
      if (Arrays.deepEquals(mat, target))
        return true;
      rotate(mat);
    }
    return false;
  }

  private void rotate(int[][] mat) {
    for (int i = 0, j = mat.length - 1; i < j; ++i, --j) {
      int[] temp = mat[i];
      mat[i] = mat[j];
      mat[j] = temp;
    }
    for (int i = 0; i < mat.length; ++i)
      for (int j = i + 1; j < mat.length; ++j) {
        final int temp = mat[i][j];
        mat[i][j] = mat[j][i];
        mat[j][i] = temp;
      }
  }
}
1
2
3
4
5
6
7
class Solution:
  def findRotation(self, mat: list[list[int]], target: list[list[int]]) -> bool:
    for _ in range(4):
      if mat == target:
        return True
      mat = [list(x) for x in zip(*mat[::-1])]
    return False