ALGORITHM

백준 11650 좌표 정렬하기 (Java)

공부하는_다온 2023. 3. 11. 22:01

1. 문제 링크

 

11650번: 좌표 정렬하기

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

www.acmicpc.net

 

2. 문제 및 입출력예제

 

3. 문제 풀이

좌표를 정렬하기 위해 클래스를 만들어서 x, y를 관리했다.

정렬을 위해 클래스에 Comparable 인터페이스를 구현한다.

그 중 compareTo()를 재정의해 x좌표 비교 후 y좌표를 비교하도록 했다.

이후에 Arrays.sort()를 이용해 배열을 재정의한 순으로 정렬한다.

 

4. 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;

public class Main {
	static class Point implements Comparable<Point>{
		int x;
		int y;
		
		public Point(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}

		@Override
		public int compareTo(Point o) {
			if(this.x > o.x) {
				return 1;
			}
			else if(this.x < o.x) {
				return -1;
			}
			else {
				 if(this.y > o.y) {
					 return 1;
				 }
				 else {
					 return -1;
				 }
			}
		}
	}
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int N = Integer.parseInt(br.readLine());
		Point[] p = new Point[N];
		String[] split = new String[2];
		for(int i=0;i<N;i++) {
			split = br.readLine().split(" ");
			p[i] = new Point(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
		}
		Arrays.sort(p);
		for(Point a: p) {
			sb.append(a.x+" "+ a.y).append("\n");
		}
		System.out.println(sb);
	}	
}