문제

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

입력

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

출력

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

 

나의 풀이

 문제의 접근방법으로는 Collection의 sort를 사용하기 위해 class에 비교함수를 오버라이드 할 수 있는지라고 생각하고 접근. 받은 값에 따라 Point class의 객체를 생성하고 list에 저장했다. Point class에는 x값이 클수록, y값이 클수록 우선순위가 높도록 compareTo 메서드를 오버라이드 하고 list를 정렬 후 출력했다. java다운 코드 느낌이라 재밌게 금방 풀었다.

코드

import java.util.*;
import java.io.*;

class Point implements Comparable<Point>{
    
    int x;
    int y;
    
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    @Override
    public int compareTo(Point p2) {
        if(this.x>p2.x) {
            return 1;
        } else if(this.x<p2.x){
            return -1;
        } else {
            if(this.y>p2.y) {
                return 1;
            } else if(this.y<p2.y) {
                return -1;
            } else {
                return 0;
            }
        }
    }
    
    @Override
    public String toString() {
        return x+" "+y;
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int num = Integer.parseInt(br.readLine());
        StringTokenizer st;
        List<Point> list = new ArrayList<>();
        for(int i =0; i<num; i++) {
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            list.add(new Point(x,y));
        }
        
        Collections.sort(list);
        for(int i=0; i<list.size(); i++) {
            bw.write(list.get(i).toString() + "\n");
        }
        
        bw.flush();
    }
}

+ Recent posts