티스토리 뷰

728x90

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

 

1913번: 달팽이

N개의 줄에 걸쳐 표를 출력한다. 각 줄에 N개의 자연수를 한 칸씩 띄어서 출력하면 되며, 자릿수를 맞출 필요가 없다. N+1번째 줄에는 입력받은 자연수의 좌표를 나타내는 두 정수를 한 칸 띄어서

www.acmicpc.net

 

방향을 가리키는 변수 설정이 중요한 문제입니다.

행이 증가할 땐, 으로

열이 증가할 땐, 우측으로 증가하는 특성을 이용해서 달팽이 모양을 만들 때, 하단 + 오른쪽 (+) / 상단 + 왼쪽 (-)

으로 움직이게 방향 값을 설정한 뒤, 주어진 M 값이 있는 위치를 출력하면 되는 문제입니다.

 

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
import java.util.*;
 
public class Main {
    static int arr[][];
    static int N = 0, M = 0;
    static StringBuilder sb = new StringBuilder();
 
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
 
        arr = new int[N][N];
        int dir = 1, row = -1, col = 0;
        int x = 0, y = 0;
        int n = N * N;
        int origin_n = N;
 
        while (N > 0) {
            for (int i = 0; i < N; i++) {
                row += dir;
                arr[row][col] = n;
                if (chk_num(row, col)) {
                    x = row + 1;
                    y = col + 1;
                }
                n--;
            }
            N--;
 
            for (int j = 0; j < N; j++) {
                col += dir;
                arr[row][col] = n;
                if (chk_num(row, col)) {
                    x = row + 1;
                    y = col + 1;
                }
                n--;
            }
            dir *= -1;
 
        }
 
        for (int i = 0; i < origin_n; i++) {
            for (int j = 0; j < origin_n; j++) {
                sb.append(arr[i][j] + " ");
            }
            sb.append("\n");
        }
        sb.append(x + " " + y);
        System.out.print(sb);
        sc.close();
    }
 
    private static boolean chk_num(int x, int y) {
        if (arr[x][y] == M) {
            return true;
        }
        return false;
    }
}
cs

 

댓글