[Lv.1] 좌표 정렬하기 2

박준원·2024년 4월 6일

정렬

목록 보기
8/12

문제 이해

2차원 평면 위의 점 N개가 주어졌을 때, 좌표를 y좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순서로 정렬하여 출력하는 문제입니다.

알고리즘 설계

  1. 주어진 점들을 Point 객체로 표현합니다. 이 때, Point 클래스는 x좌표와 y좌표를 멤버 변수로 가집니다.
  2. Comparator 인터페이스를 구현하여 y좌표를 기준으로 정렬합니다. y좌표가 같은 경우 x좌표로 오름차순으로 정렬합니다.
  3. Arrays.sort() 메서드를 이용하여 정렬을 수행합니다.
    정렬된 결과를 출력합니다.

소스 코드 구현

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

class Point {
    int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());
        Point[] points = new Point[N];

        // 점들을 Point 객체로 생성하여 배열에 저장
        for (int i = 0; i < N; i++) {
            String[] input = br.readLine().split(" ");
            int x = Integer.parseInt(input[0]);
            int y = Integer.parseInt(input[1]);
            points[i] = new Point(x, y);
        }

        // Comparator를 이용한 정렬
        Arrays.sort(points, new Comparator<Point>() {
            @Override
            public int compare(Point p1, Point p2) {
                if (p1.y == p2.y) {
                    return Integer.compare(p1.x, p2.x);
                }
                return Integer.compare(p1.y, p2.y);
            }
        });

        // 정렬된 점들을 출력
        for (Point point : points) {
            System.out.println(point.x + " " + point.y);
        }
    }
}

소스 분석

이 코드는 주어진 점들을 y좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순서로 정렬하는 기능을 수행합니다. 먼저 입력된 점들을 Point 객체로 생성하여 배열에 저장합니다. 그 후, Comparator를 이용하여 정렬을 수행합니다. Comparator는 y좌표를 기준으로 비교하며, y좌표가 같은 경우 x좌표를 비교하여 정렬합니다. 이렇게 정렬된 점들을 출력하여 문제의 조건에 맞는 결과를 얻습니다.

profile
08년생 Programmer - C++, Java, Kotlin

0개의 댓글