[프로그래머스, 181832] 정수를 나선형으로 배치하기 (java)
Problem Solving/Programmers

[프로그래머스, 181832] 정수를 나선형으로 배치하기 (java)

728x90

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

728x90

메모리: 82.1 MB, 시간: 0.09 ms

사용 알고리즘: 구현, 사방탐색

class Solution {
    public int[][] solution(int n) {
        
        int[][] answer = new int[n][n];
        
        // 우하좌상
        int[] dx = new int[] {0, 1, 0, -1};
        int[] dy = new int[] {1, 0, -1, 0};
        
        // 현재 위치와 방향
        int x = 0, y = -1, d = 0;
        
        int nx, ny;
        for(int i = 1; i <= n * n; i++) {
            nx = x + dx[d];
            ny = y + dy[d];
            
            // 범위를 넘어가거나 이미 방문한 곳이라면 위치 조정
            if(nx < 0 || nx >= n || ny < 0 || ny >= n || answer[nx][ny] != 0) {
                d = d == 3 ? 0 : d + 1;
                nx = x + dx[d];
                ny = y + dy[d];
            }
            
            // 이동
            x = nx;
            y = ny;
            answer[x][y] = i;
        }
        
        return answer;
    }
}
728x90