[ 문제 ]
2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
[ 입력 ]
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
[ 출력 ]
첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.
[ 풀이 ]
Point 클래스
Main 클래스
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
class Point implements Comparable<Point>{
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString(){ // 출력을 위한 오버라이딩
return this.x + " " + this.y;
}
@Override
public int compareTo(Point p) {
if(this.x > p.x){
return 1;
}
else if (this.x == p.x) {
if(this.y > p.y)
return 1;
else
return -1;
}
else {
return -1;
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
// 0
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
ArrayList<Point> points = new ArrayList<>();
// 1
int N = Integer.parseInt(br.readLine());
// 2
for(int i=0; i<N; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
points.add(new Point(x, y));
}
// 3
Collections.sort(points);
// 4
for(Point p : points)
System.out.println(p);
}
}
[ 배운 것 ]
Comparable 인터페이스
compareTo 메소드
[ 실행 결과 ]