[백준] 1022번 소용돌이 예쁘게 출력하기 (자바 풀이)

문제

https://www.acmicpc.net/problem/1022

 

1022번: 소용돌이 예쁘게 출력하기

첫째 줄에 네 정수 r1, c1, r2, c2가 주어진다.

www.acmicpc.net

 

풀이

모든 숫자를 계산해서 저장하는 것은 메모리의 한계로 가능하지 않다(10000*10000=1억 개의 int)

 

따라서 숫자는 계속해서 계산해나가면서, 범위에 있는 배열에만 값을 저장하면 된다.

 

이때 map[r2-r1+1][c2-c1+1] 을 선언해서 사용하면 된다. 

 

자세한 내용은 코드를 참고하자.

 

 

코드

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.io.*;
import java.util.Scanner;
 
public class Baekjoon_1022 {
    static int r1,c1,r2,c2,max=0;
    static int map[][];
    static int[] dx = {0,-1,0,1};
    static int[] dy = {1,0,-1,0};
    
    public static void main(String[] args) {
        Scanner sc  = new Scanner(System.in);
        
        r1 = sc.nextInt();
        c1 = sc.nextInt();
        r2 = sc.nextInt();
        c2 = sc.nextInt();
        
        map = new int[r2-r1+1][c2-c1+1];
        
        fill();
        print();
        
        
    }
    
    public static void fill() {
        int x=0, y=0, dir=0;
        int num=1, len =1, cnt =0;
        
        while(!endCheck()) {
            if(x >= r1 && x<=r2 && y>= c1 && y <= c2) {    // 범위내에 오면
                map[x-r1][y-c1] = num;
            }
            
            num++;
            cnt++;
            x = x + dx[dir];
            y = y + dy[dir];
            
            if(cnt == len) {
                cnt = 0;
                if(dir == 1 || dir == 3) {    // 방향이 위나 아래였으면 길이가 1 증가됨
                    len++;
                }
                dir = (dir+1)%4// 방향 전환
            }
        }
        max = num - 1;     // 최댓값 저장
    }
    
    /* 원하는 좌표에 값이 모두 채워졌는지 확인 */
    public static boolean endCheck() {
        return map[0][0!= 0 && map[r2-r1][0!= 0 && map[0][c2-c1]!=0 && map[r2-r1][c2-c1]!=0;
    }
    
    public static void print() {
        int maxLen = (int)Math.log10(max);    // 자릿수 계산
        int len;
        
        for(int i=0; i<=r2-r1; i++) {
            for(int j=0; j<= c2-c1; j++) {
                len = maxLen - (int) Math.log10(map[i][j]);    // 최댓값 자릿수와 차이 계산
                for(int k=0; k<len; k++) {    // 차이만큼 공백 붙여주기
                    System.out.print(" ");
                }
                System.out.print(map[i][j]+ " ");
            }
            System.out.println();
        }
    }
 
}
cs

 

반응형

댓글

Designed by JB FACTORY