Notice
Recent Posts
Recent Comments
Link
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

main

[백준-11651번/Java] 좌표 정렬하기 2 본문

Algorithm

[백준-11651번/Java] 좌표 정렬하기 2

1984 2022. 11. 17. 22:56

* 백준 11650번 문제와 같다. (정렬 기준이 x좌표 우선인지/ y좌표 우선인지 차이)

https://main.tistory.com/209

 

[백준-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
Comments