[LeetCode] Determine Whether Matrix Can Be Obtained By Rotation

아르당·2026년 7월 15일

LeetCode

목록 보기
404/579
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

2개의 이진 행렬 mat와 target이 주어졌을때, mat를 90도 회전시켜서 target과 같게 할 수 있다면 true, 그렇지 않다면 false를 반환해라.

Example

#1

Input: mat = [[0, 1], [1, 0]], target = [[1, 0], [0, 1]]
Output: true
Explanation: mat를 시계 방향으로 90도 회전시키면 target과 같게 할 수 있다.

#2

Input: mat = [[0, 1], [1, 1]], target = [[1, 0], [0, 1]]
Output: false
Explanation: mat를 회전시켜도 target과 같게 할 수 없다.

#3

Input: mat = [[0, 0, 0], [0, 1, 0], [1, 1, 1]], target = [[1, 1, 1], [0, 1, 0], [0, 0, 0]]
Output: true
Explanation: mat를 시계 방향으로 2번 회전하면 target과 같게 할 수 있다.

Constraints

  • n == mat.length == target.length
  • n == mat[i].length == target[i].length
  • 1 <= n <= 10
  • mat[i][j]와 target[i][j]는 0 또는 1이다.

Solved

class Solution {
    public boolean findRotation(int[][] mat, int[][] target) {
        for(int i = 0; i < 4; i++){
            if(isEqual(mat, target)){
                return true;
            }

            rotate(mat);
        }

        return false;
    }

    private void rotate(int[][] mat){
        int n = mat.length;

        for(int i = 0; i < n; i++){
            for(int j = i + 1; j < n; j++){
                int temp = mat[i][j];
                mat[i][j] = mat[j][i];
                mat[j][i] = temp;
            }
        }

        for(int i = 0; i < n; i++){
            for(int j = 0; j < n / 2; j++){
                int temp = mat[i][j];
                mat[i][j] = mat[i][n - 1 - j];
                mat[i][n - 1 - j] = temp;
            }
        }
    }

    private boolean isEqual(int[][] mat, int[][] target){
        for(int i = 0; i < mat.length; i++){
            for(int j = 0; j < mat[0].length; j++){
                if(mat[i][j] != target[i][j]){
                    return false;
                }
            }
        }

        return true;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글