본문 바로가기

알고리즘/리트코드

54. Spiral Matrix

유명한 돌아가는 문제이다. (소용돌이 문제 같은 느낌)

이문제는 단순하게 노동하는 방법도 존재하지만 엄청 이쁜 풀이도 존재한다. 우선 이쁜 풀이를 보자.

const spiralOrder = function(matrix) {
  const res = []
  while(matrix.length){
    const first = matrix.shift()
    res.push(...first)
    for(const m of matrix){
      let val = m.pop()
      if(val)
        res.push(val)
        m.reverse()   
    }
    matrix.reverse()
  }
  return res
};

첫라인은 그대로 출력하고 배열에서 없앤다. 두번째 라인부터 마지막 라인까지 마지막꺼 출력하고 뒤집어 놓는다. 그다음에 전체 매트릭스를 뒤집는다. 그러면 마지막 라인이 맨위로 올라올 것이고, 다시 맨위 라인부터 마지막 라인까지 같은 작업을 반복한다.

다음으로는 국룰 풀이이다. 빙빙 도는~

const spiralOrder = function(matrix) {
    if (matrix.length == 0) return [];

    let res = [];
    let row1 = 0, col1 = 0, row2 = matrix.length-1, col2 = matrix[0].length-1;

    while (row1 <= row2 && col1 <= col2) {
        for (let col = col1; col <= col2; col++) {
            res.push(matrix[row1][col]);    
        }
        for (let row = row1+1; row <= row2; row++) {
            res.push(matrix[row][col2]);
        }
        if (row1 < row2 && col1 < col2) {
            for (let col = col2-1; col >= col1; col--) {
                res.push(matrix[row2][col]);
            }
            for (let row = row2-1; row > row1; row--) {
                res.push(matrix[row][col1]);
            }    
        }

        row1++, col1++, row2--, col2--;
    }

    return res;
};

'알고리즘 > 리트코드' 카테고리의 다른 글

43. Multiply Strings  (0) 2022.09.12
139. Word Break  (0) 2022.05.08
22. Generate Parentheses  (0) 2022.04.16
33. Search in Rotated Sorted Array  (0) 2022.04.15
289. Game of Life  (0) 2022.04.13