본문 바로가기
프로그래밍/알고리즘, 프로그래밍 언어

[코딩테스트] 나선형 순회 spiralTraversal (JavaScript)

by 제이콥J 2022. 2. 7.

문제

설명

Take a two-dimensional array(i.e., an array containing many arrays of equal length) and return all the values in the array.

조건

The spiral turns clockwise (start left -> right)

All elements of an array contain only numbers

Empty arrays are not entered

Based on the entire two-dimensional array, there are no identical elements(the same number).

예시

spiralTraversal([
  [1,2,3],
  [4,5,6],
  [7,8,9]
]);

returns [1, 2, 3, 6, 9, 8, 7, 4, 5]

 

솔루션

행(row)과 열(column) 각각 시작 인덱스와 마지막 인덱스를 변수로 선언하기

2차원 배열을 시계방향으로 순회하며, 시작 인덱스와 마지막 인덱스를 변경하기

시작 인덱스가 마지막 인덱스보다 커지게 되면, 모든 엘리먼트를 순회했기 때문에 반복문을 종료하기

 

function test(matrix) {

  let results = [];
  let startRowIndex = 0;
  let endRowIndex = matrix.length - 1;
  let startColIndex = 0;
  let endColIndex = matrix[0].length - 1;

  while (startRowIndex <= endRowIndex && startColIndex <= endColIndex) {

    for (let i = startColIndex; i <= endColIndex; i++) {
      results.push(matrix[startRowIndex][i]);
    }
    // 가장 위 행의 엘리먼트를 모두 순회했기 때문에, 시작 인덱스를 한 칸 아래로 이동
    startRowIndex++;  

    for (let j = startRowIndex; j <= endRowIndex; j++) {
      results.push(matrix[j][endColIndex]);
    }
    // 가장 오른쪽 열이 엘리먼트를 모두 순회했기 때문에, 마지막 인덱스를 왼쪽으로 한 칸 이동
    endColIndex--;  

    if (startRowIndex <= endRowIndex) {
      for (let k = endColIndex; k >= startColIndex; k--) {
        results.push(matrix[endRowIndex][k]);
      }
      endRowIndex--;
    }

    if (startColIndex <= endColIndex) {
      for (let m = endRowIndex; m >= startRowIndex; m--) {
        results.push(matrix[m][startColIndex]);
      }
      startColIndex++;
    }

  }

  return results;
};

 

 

 

 

반응형

댓글