90도 회전하는 배열 매트릭스

2020. 10. 22. 00:56알고리즘

const matrix = [
[1,2,3,4],
[5,6,7,8],
[9,'A','B','C'],
['D','E','F','G']
];
matrix[0][0]; // 1
matrix[3][2]; // 'F'

const rotatedMatrix = rotateMatrix(matrix); // Rotate 90 degrees clockwise
// rotatedMatrix is:
[ ['D',9,5,1],
['E','A',6,2],
['F','B',7,3],
['G','C',8,4]
]

//위와 같은 결과를 얻고 싶다!
const rotateMatrix = function (matrix, direction) {
  // NxN 매트릭스를 90도로 회전시키는 함수를 작성하세요.

  direction = direction || 1;
  let m = matrix.length;
  //세로로 얼마나 길게 있는지 m으로 표현
  let n = matrix[0] && matrix[0].length;
  // 가로가 얼마나 길게 있는지 n으로 표현!
  let output = [];
  // We iterate with i,j in output order to transparently support rectangular arrays
  for (var i = 0; i < n; i++) {
    output[i] = [];
    // 주어진 행렬의 가로 만큼 아웃풋에도 빈 배열 추가.
    for (var j = 0; j < m; j++) {
      if (direction > 0) {
        // rotate clockwise 시계방향으로 회전
        // 기존에서 세로 마지막 첫 가로를 넣고 그 다음으로 세로방향 애들을 넣어야하기 때문에 아래처럼 식 작성.
        output[i][j] = matrix[m - j - 1][i];
      } else if (direction < 0) {
        // rotate counterclockwise
        //기존에서 가로의 마지막 줄에 행당하는 세로들을 위에서 아래로 넣어야하기 때문에 아래처럼 식 작성! 
        output[i][j] = matrix[j][n - i - 1];
      }
    }
  }
  return output;
};

'알고리즘' 카테고리의 다른 글

countIslands  (0) 2020.11.20
isPalindromeLL  (0) 2020.11.16
(function(){})() 이 구조는??  (0) 2020.11.11
Robot Paths (feat.로봇청소기야 너 굉장히 고생하고 있었구나 ㅠㅠ)  (0) 2020.10.31
[0] 알고리즘?  (0) 2020.09.14