2차원 평면 위의 점 N개가 주어졌을 때, 좌표를 y좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순서로 정렬하여 출력하는 문제입니다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Point[] points = new Point[N];
// 점들을 Point 객체로 생성하여 배열에 저장
for (int i = 0; i < N; i++) {
String[] input = br.readLine().split(" ");
int x = Integer.parseInt(input[0]);
int y = Integer.parseInt(input[1]);
points[i] = new Point(x, y);
}
// Comparator를 이용한 정렬
Arrays.sort(points, new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
if (p1.y == p2.y) {
return Integer.compare(p1.x, p2.x);
}
return Integer.compare(p1.y, p2.y);
}
});
// 정렬된 점들을 출력
for (Point point : points) {
System.out.println(point.x + " " + point.y);
}
}
}
이 코드는 주어진 점들을 y좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순서로 정렬하는 기능을 수행합니다. 먼저 입력된 점들을 Point 객체로 생성하여 배열에 저장합니다. 그 후, Comparator를 이용하여 정렬을 수행합니다. Comparator는 y좌표를 기준으로 비교하며, y좌표가 같은 경우 x좌표를 비교하여 정렬합니다. 이렇게 정렬된 점들을 출력하여 문제의 조건에 맞는 결과를 얻습니다.