CodeWars 코딩 문제 2021/01/29 - Snail

이호현·2021년 1월 29일
0

Algorithm

목록 보기
72/138

[문제]

Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

For better understanding, please follow the numbers of the next array consecutively:

This image will illustrate things more clearly:

NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.

NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]].

(요약) 시계방향으로 달팽이 모양으로 돌면서 만나는 숫자들을 배열에 넣고 return/

[풀이]

snail = function(array) {
  const answer = [];
  const length = array.length * array[0].length;
  let direction = 'r';
  let row = 0;
  let col = 0;
  array.push(new Array(array[0].length).fill('#'));

  for(let i = 0; i < length; i++) {
    answer.push(array[row][col]);
    array[row][col] = '#';

    const [tempRow, tempCol] = nextP(row, col, direction);

    if(array[tempRow][tempCol] === '#' || !array[tempRow][tempCol]) {
      direction = setDir(direction);
      [row, col] = nextP(row, col, direction);
    }
    else {
      row = tempRow;
      col = tempCol;
    }
  }

  return answer;
}

// 한 칸씩 움직이는 함수
function nextP(r, c, dir) {
  if(dir === 'r') {
    return [r, ++c];
  }
  else if(dir === 'd') {
    return [++r, c];
  }
  else if(dir === 'l') {
    return [r, --c];
  }
  else {
    return [--r, c];
  }
}

// 방향 바꾸는 함수
function setDir(dir) {
  const directionArr = ['r', 'd', 'l', 'u'];
  let dirIndex = directionArr.indexOf(dir);

  if(dirIndex < 3) {
    return directionArr[++dirIndex];
  }
  else {
    return directionArr[0];
  }
}

방향이 정해졌을 때 한 칸씩 이동하는 함수, 방향을 바꾸는 함수를 먼저 정의.
반복문을 이용해서 한 칸씩 이동시키고 끝에 닿으면 방향을 바꾸는 함수를 호출.
만나는 숫자는 answerpush하고, 그 자리에 #로 덮어 씀.
array의 마지막을 #로 채운 이유는 array의 마지막 배열 다음 요소에서 찾으려고 하면 에러가 나서 넣어둠.
그래서 달팽이 모양으로 돌면서 숫자를 수집하고 결과값을 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글