본문 바로가기

Tech/[PS] Reviews

[프로그래머스-코딩 기초 트레이닝] 정수를 나선형으로 배치하기

Hi, There!
안녕하세요, 바오밥입니다.

 


목차

  • 문제
  • 풀이

 


문제

문제 내용

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

 

프로그래머스

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

programmers.co.kr

 


풀이

나의 풀이

class Solution {
    public int[][] solution(int n) {
        int[][] answer = new int[n][n];
        
        int cnt = 1;
        int colStart = 0;
        int colEnd = n-1;
        int rowStart = 0;
        int rowEnd = n-1;
        
        while(cnt<=n*n) {
            for(int i=colStart; i<=colEnd; i++) answer[rowStart][i] = cnt++; // right
            rowStart++;
            
            for(int i=rowStart; i<=rowEnd; i++) answer[i][colEnd] = cnt++; // down
            colEnd--;
            
            for(int i=colEnd; i>=colStart; i--) answer[rowEnd][i] = cnt++; // left
            rowEnd--;
            
            for(int i=rowEnd; i>=rowStart; i--) answer[i][colStart] = cnt++; // up
            colStart++;
        }
        
        return answer;
    }
}

 

다른 사람의 풀이

class Solution {
    public int[][] solution(int n) {
        int[][] answer = new int[n][n];
        int num = 1;
        int x = 0, y = 0;
        int dx[] = {0, 1, 0, -1};
        int dy[] = {1, 0, -1, 0};
        int direction = 0;

        while (num <= n * n) {
            answer[x][y] = num++;

            int nx = x + dx[direction]; 
            int ny = y + dy[direction];

            if (nx < 0 || nx >= n || ny < 0 || ny >= n || answer[nx][ny] != 0) {
                direction = (direction + 1) % 4; //범위 밖에 나갔을 때 방향전환
                nx = x + dx[direction];
                ny = y + dy[direction];
            }
            x = nx;
            y = ny;
        }

        return answer;
    }
}

// right-> down -> left -> up 이동 경로를 dx, dy에 각각 저장해 순서대로 반복하는 알고리즘

 

 

Reference

https://velog.io/@js4183/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-Lv.0-%EC%A0%95%EC%88%98%EB%A5%BC-%EB%82%98%EC%84%A0%ED%98%95%EC%9C%BC%EB%A1%9C-%EB%B0%B0%EC%B9%98%ED%95%98%EA%B8%B0.java

 

[프로그래머스] Lv.0 정수를 나선형으로 배치하기.java

출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges

velog.io