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>>& M) {
    reverse(begin(M), end(M));
    for (int i = 0; i < M.size(); ++i)
      for (int j = i + 1; j < M.size(); ++j)
        swap(M[i][j], M[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[][] M) {
    for (int i = 0, j = M.length - 1; i < j; ++i, --j) {
      int[] temp = M[i];
      M[i] = M[j];
      M[j] = temp;
    }
    for (int i = 0; i < M.length; ++i)
      for (int j = i + 1; j < M.length; ++j) {
        final int temp = M[i][j];
        M[i][j] = M[j][i];
        M[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
Back to top