Algorithm
[백준-11651번/Java] 좌표 정렬하기 2
1984
2022. 11. 17. 22:56
* 백준 11650번 문제와 같다. (정렬 기준이 x좌표 우선인지/ y좌표 우선인지 차이)
[백준-11650번/Java] 좌표 정렬하기
* Interface Comparable, copareTo method override 하여 좌표를 정렬하였다. import java.io.*; import java.util.*; public class Main { private static class Point implements Comparable { int x; int y; public Point(int x, int y) { this.x = x; this.y =
main.tistory.com
* y좌표를 우선적으로 정렬 기준이 되도록 compareTo() method 를 수정했다.
import java.io.*;
import java.util.*;
public class Main {
private static class Point implements Comparable {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Integer getX() {
return this.x;
}
public Integer getY() {
return this.y;
}
@Override
public boolean equals(Object o) {
Point p = (Point) o;
return p.getX() == getX() && p.getY() == getY();
}
@Override
public int compareTo(Object o) {
Point p = (Point) o;
return Comparator.comparing(Point::getY).thenComparing(Point::getX).compare(this, p);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return getX() + " " + getY();
}
}
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
ArrayList<Point> pointList = new ArrayList<Point>();
for (int i = 0; i < N; i++) {
StringTokenizer stk = new StringTokenizer(br.readLine());
pointList.add(new Point(Integer.parseInt(stk.nextToken()), Integer.parseInt(stk.nextToken())));
}
Collections.sort(pointList);
for (Point point : pointList) {
System.out.println(point.toString());
}
}
}
728x90