문제
2차원 평면 위의 점 N개가 주어진다. 좌표를 y좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
출력
첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.
예제 입력 1
5
0 4
1 2
1 -1
2 2
3 3
예제 출력 1
1 -1
1 2
2 2
3 3
0 4
풀이
import java.awt.Point;
import java.io.IOException;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
int n = readInt();
StringBuilder sb = new StringBuilder();
Point[] points = new Point[n];
int x; int y;
for(int i = 0; i < n; i++){
x = readInt();
y = readInt();
points[i] = new Point(x, y);
}
Arrays.sort(points, (p1, p2) -> {
if (p1.y != p2.y) {
return Integer.compare(p1.y, p2.y);
}
return Integer.compare(p1.x, p2.x);
});
for (Point p : points) {
sb.append(p.x + " " + p.y+"\n");
}
System.out.println(sb.toString());
}
private static int readInt() throws IOException {
int out = 0;
boolean negative = false;
while (true) {
int n = System.in.read();
if(n<=32) return negative? (-1)*out:out;
else if (n == '-') negative = true;
else out = (out <<3) + (out<<1) + (n-'0');
}
}
}
Point : 자바에서 좌표(두 값)를 담기 위한 클래스
- x, y 두 개의 정수 값을 한 묶음으로 표현
- 좌표, 위치, (n, m) 같은 데이터 표현에 자주 사용
내부 구조:
public class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
'Coding Test > 백준 - JAVA' 카테고리의 다른 글
| 백준 1620번 나는야 포켓몬 마스터 이다솜 (JAVA) (1) | 2026.01.23 |
|---|---|
| 백준 1181번 단어 정렬 (JAVA) (0) | 2026.01.16 |
| 백준 11650번 좌표 정렬하기(JAVA) (0) | 2026.01.04 |
| 백준 2751번 수 정렬하기2 (JAVA) (2) | 2025.03.03 |
| 백준 25305번 커트라인 (JAVA) (0) | 2025.02.26 |