[LeetCode] Determine Whether Matrix Can Be Obtained By Rotation

준규·2023년 1월 4일
0

1.문제


Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.


두개의 nxn 행렬인 mat과 target이 주어질 때 mat 행렬을 회전시켜서 target행렬로 만들 수 있으면 true를 리턴하는 문제이다.


Example 1

Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
Output: true
Explanation: We can rotate mat 90 degrees clockwise to make mat equal target.

Example 2

Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
Output: false
Explanation: It is impossible to make mat equal to target by rotating mat.

Example 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: We can rotate mat 90 degrees clockwise two times to make mat equal target.

Constraints:

  • n == mat.length == target.length
  • n == mat[i].length == target[i].length
  • 1 <= n <= 10
  • mat[i][j] and target[i][j] are either 0 or 1.

2.풀이

  1. 행렬을 90도씩 돌리면서 target 행렬과 비교를 한다.
  2. 모든 원소값이 target행렬의 값과 같다면 true를 리턴해준다.

/**
 * @param {number[][]} mat
 * @param {number[][]} target
 * @return {boolean}
 */
const findRotation = function (mat, target) {
  let result = true;
  // nxn 행렬을 시계 방향으로 90도 회전하는 함수
  const rotate = (matrix) => {
    const rotateMatrix = [];
    // 요소가 전부 0인 nxn 빈 행렬 생성
    for (let i = 0; i < matrix.length; i++) {
      const row = [];
      for (let j = 0; j < matrix.length; j++) {
        row.push(0);
      }
      rotateMatrix.push(row);
    }

    for (let i = 0; i < matrix.length; i++) {
      for (let j = 0; j < matrix[0].length; j++) {
        rotateMatrix[j][matrix.length - 1 - i] = matrix[i][j];
      }
    }

    return rotateMatrix;
  };

  let rotatedMatrix = rotate(mat);

  for (let k = 0; k < 4; k++) {
    result = true;
    // target 행렬과 회전한 행렬을 비교한다
    for (let i = 0; i < target.length; i++) {
      for (let j = 0; j < target.length; j++) {
        if (rotatedMatrix[i][j] !== target[i][j]) {
          result = false;
        }
      }
    }

    // 만약 비교를 해서 target 행렬과 동일하다면 true를 리턴한다.
    if (result) {
      return result;
    } else {
      rotatedMatrix = rotate(rotatedMatrix);

      continue;
    }
  }

  return result;
};

3.결과

profile
안녕하세요 :)

0개의 댓글