코테/프로그래머스

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

imname1am 2023. 10. 10. 23:48
반응형

🔺 문제

 

프로그래머스

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

programmers.co.kr

 

 

🔺 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.*;
 
class Solution {    
    static int val = 1;
    static int row, col;    // 현재 행, 열 위치
    static int dir = 0;     // 방향 (0 : 오른쪽 / 1 : 아래 / 2 : 왼쪽 / 3 : 위쪽)
    
    public int[][] solution(int n) {
        int[][] answer = new int[n][n];
        
        while(val <= n * n) {   // 모두 채워질 때까지 반복
            answer[row][col] = val++;
            
            // 다음 이동할 위치 계산
            if(dir == 0) {  // 오른쪽 방향으로 이동
                if(col == n - 1 || answer[row][col + 1!= 0) {
                    dir = 1;
                    row++;
                }
                else {
                    col++;
                }
            }
            else if(dir == 1) { // 아래쪽 방향으로 이동
                if(row == n - 1 || answer[row + 1][col] != 0) {
                    dir = 2;
                    col--;
                }
                else {
                    row++;
                }
            }
            else if(dir == 2) { // 왼쪽 방향으로 이동
                if(col == 0 || answer[row][col - 1!= 0) {
                    dir = 3;
                    row--;
                }
                else {
                    col--;
                }
            }
            else if(dir == 3) { // 위쪽 방향으로 이동
                if(row == 0 || answer[row - 1][col] != 0) {
                    dir = 0;
                    col++;
                }
                else {
                    row--;
                }
            }
        }
        
        
        return answer;
    }
}
cs

 

 

🧩 해결 아이디어

• 구현

1. 배열을 n x n 크기로 설정한다.

2. while문을 활용해 칸이 모두 채워질 때까지 반복한다.

3. 방향을 나타내는 변수 dir을 활용해 한 줄씩 반복한다. => 값이 있거나, 끝자리에 있는 값이라면 dir 값을 바꾸고 반복

 

 


🔺 다른 풀이들

- 완전 깔꼼한... dx/dy를 활용하셨다.

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;
    }
}

 

 

- 한 칸 한 칸 배열의 값을 반복문으로 +1씩 하면서 값을 채우심

class Solution {
    public int[][] solution(int n) {
        int[][] answer = new int[n][n];
        int num=1;
        int start=0;
        int end=n;

        while(num <= n*n){

            //->
            for(int j=start;j<end;j++)
                answer[start][j]=num++;
            //v
            for(int i=start+1;i<end;i++)
                answer[i][end-1]=num++;
            //<
            for(int j=end-2;j>=start;j--)
                answer[end-1][j]=num++;
            //^
            for(int i=end-2;i>start;i--)
                answer[i][start]=num++;
                
            start++;
            end--;
        }

        return answer;
    }
}

💬 느낀 점

이런 달팽이 문제는 처음 풀어보는디......

여러번 반복하면 풀 수 나 혼자서도 있을지도!!!

(이번 모 기업의 코테에 비슷한 문제 나왔대서 풀어봤다)

 

1회독 2회독 3회독 4회독 5회독
V 12.27 240219    

 

 

(+12.27 2회독)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;
 
class Solution {
    static int n;
    
    static int[] dx = {0,1,0,-1};   // 동남서북
    static int[] dy = {1,0,-1,0};
    
    public int[][] solution(int n) {
        this.n = n;
        int[][] answer = new int[n][n];
        
        answer[0][0= 1;
        int dir = 0;
        
        int x = 0;
        int y = 0;
        
        for(int i = 2 ; i <= n * n ; i++) {
            int nx = x + dx[dir];
            int ny = y + dy[dir];
            
            if(!inRange(nx, ny) || answer[nx][ny] != 0) {
                dir = (dir + 1) % 4;
            }
            
            x += dx[dir];
            y += dy[dir];
            answer[x][y] = i;            
        }        
        
        return answer;
    }
    
    private static boolean inRange(int r, int c) {
        return (0 <= r && r < n && 0 <= c && c < n);
    }
}
cs

 

 

(+240219 3회독)

15분 소요,,

코드 확인하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.*;
 
class Solution {
    static int n;
    
    static int[] dx = {010-1};   // 동남서북
    static int[] dy = {10-10};
    
    public int[][] solution(int n) {
        this.n = n;
        
        int[][] answer = new int[n][n];
        
        int x = 0;
        int y = 0;
        int dir = 0;
        int num = 1;
 
        answer[x][y] = num;
        
        while(num < n*n) {
            int nx = x + dx[dir];
            int ny = y + dy[dir];
            
            if(!inRange(nx, ny) || answer[nx][ny] != 0) {
                dir = (dir + 1) % 4;
            }
                        
            x += dx[dir];
            y += dy[dir];
            answer[x][y] = ++num;
        }
        
        return answer;
    }
    
    private static boolean inRange(int x, int y) {
        return (0 <= x && x < n && 0 <= y && y < n);
    }
}
cs

 


(참고)

 

[프로그래머스] 정수를 나선형으로 배치하기 | Java - 민민의 하드디스크 - 티스토리

정수를 나선형으로 배치하기 문제 설명 양의 정수 n이 매개변수로 주어집니다. n × n 배열에 1부터 n2 까지 정수를 인덱스 [0][0]부터 시계방향 나선형으로 배치한 이차원 배열을 return 하는 solution

2minmin2.tistory.com

 

반응형