개발/알고리즘(코딩테스트)

프로그래머스, 자바스크립트) 정수를 나선형으로 배치하기

빔네모 2024. 6. 16. 17:26

문제

https://school.programmers.co.kr/learn/courses/30/lessons/181832

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

풀이

우선, 0으로 채운 n x n 크기의 배열을 만들어 준다.

  // 결과를 저장할 이차원 배열을 n x n 크기로 만들기
  const result = Array.from({ length: n }, () => Array(n).fill(0));

 

나선형으로 변수를 채우기 위해 필요한 방향 변수를 정의 해놓는다.

  let num = 1;
  let row = 0, col = 0;
  let dr = 0, dc = 1; // 시작 방향: 오른쪽

다음에 for문을 사용하여 조건에 맞게 숫자를 채운다. for 문은 n x n 크기 만큼 반복된다.


  for (let i = 0; i < n * n; i++) {
    result[row][col] = num++;
    const nextRow = row + dr;
    const nextCol = col + dc;

    // 다음 위치가 범위를 벗어나거나 이미 채워진 경우 방향 전환
    if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || result[nextRow][nextCol] !== 0) {
      [dr, dc] = [dc, -dr]; // 방향을 전환 (오른쪽 -> 아래 -> 왼쪽 -> 위)
    }

    row += dr;
    col += dc;
  }

 

전체 풀이는 다음과 같다.

function solution(n) {
  const result = Array.from({ length: n }, () => Array(n).fill(0));
  let num = 1;
  let row = 0, col = 0;
  let dr = 0, dc = 1; // 시작 방향: 오른쪽

  for (let i = 0; i < n * n; i++) {
    result[row][col] = num++;
    const nextRow = row + dr;
    const nextCol = col + dc;

    // 다음 위치가 범위를 벗어나거나 이미 채워진 경우 방향 전환
    if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || result[nextRow][nextCol] !== 0) {
      [dr, dc] = [dc, -dr]; // 방향을 전환 (오른쪽 -> 아래 -> 왼쪽 -> 위)
    }

    row += dr;
    col += dc;
  }

  return result;
}

// 예시 실행
console.log(solution(4)); // [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]
console.log(solution(5)); // [[1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9]]