백준

[JAVA] 백준 11650번 좌표 정렬하기

DEV장화 2023. 4. 17. 21:59
728x90
반응형
문제

 

2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.

 

입력

 

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

 

출력

 

첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.

 

입력예제

 

5
3 4
1 1
1 -1
2 2
3 3

 

출력예제

 

1 -1
1 1
2 2
3 3
3 4

 

풀이

 


import java.io.*;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(bf.readLine());
        int[][] x = new int[n][2];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 1; j++) {
                String[] a = bf.readLine().split(" ");
                x[i][0] = Integer.parseInt(a[0]);
                x[i][1] = Integer.parseInt(a[1]);
            }
        }

        Arrays.sort(x, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0])
                    return o1[1] - o2[1];
                else
                    return o1[0] - o2[0];
            }
        });

        // 출력
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 2; j++) {
                bw.write(String.valueOf(x[i][j]) + " ");
            }
            bw.write("\n");
        }
        bw.flush();
        bw.close();
    }
}
728x90
반응형