# BOJ11650 좌표 정렬하기
https://www.acmicpc.net/problem/11650 (opens new window)
2차원 평면 위의 점 N개가 주어진다.
- x 좌표가 증가하는 순으로 정렬한다.
- x 좌표가 같으면 y 좌표가 증가하는 순으로 정렬한다.
# Location.java
좌표를 관리하기 위한 Location
클래스이다.
Location
클래스를 활용한 이유는 좌표에 대한 표현이 좀 더 직관적으로 다가오기 때문에 선호하여 사용한다.
static class Location {
int x; int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
}
# 제출 코드
정렬하기 위해 각 객체 비교를 위한 Comparator
인터페이스를 구현한다.
locations.sort((a, b) -> {
if (a.x < b.x) { // x 오름차순으로 정렬한다.
return -1;
// x가 같으면 y 좌표 오름차순으로 정렬한다.
} else if (a.x == b.x && a.y < b.y) {
return -1;
} else if (a.x == b.x && a.y == b.y) {
return 0;
}
return 1;
});
최종 제출 코드이다.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class BOJ11650 {
static class Location {
int x; int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<Location> locations = new ArrayList<>();
for (int i = 0; i < n; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
locations.add(new Location(x, y));
}
locations.sort((a, b) -> {
if (a.x < b.x) {
return -1;
} else if (a.x == b.x && a.y < b.y) {
return -1;
} else if (a.x == b.x && a.y == b.y) {
return 0;
}
return 1;
});
locations.forEach(location -> System.out.println(location.x + " " + location.y));
}
}