알고리즘 - 백준_11650번_좌표 정렬하기

jodbsgh·2023년 4월 14일
0

문제를 자세하게 봐야겠다는 생각을 일깨워준 문제였다. 입력 방법이 x따로 y따로인 줄 알았으나...
x와 y를 같이 입력한다는 사실을 모르고 문제를 풀고 제출했다... 결과는 당연히 영문도 모른채 "틀렸습니다"를 마주했다. 도저히 문제점을 못 찾겠어서 결국은 CHAT-GPT의 도움을 받았다.
내가 작성한 소스의 문제점을 알려달라고 질문하니 뜬금없이 split을 사용한 수정된 코드를 받았고 그 때서야 깨달았다. 문제를 잘못 보고 있었다는 것을...

문제가 잘 안풀릴 때는 문제를 다시 반복해서 보자.
항상 문제속에 답이 있다는 사실을 기억하자.

✅코드

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        // 입력을 위한 BufferedReader와 출력을 위한 BufferedWriter 생성
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        // 입력으로부터 n을 읽고, 크기가 n인 Point 배열 생성
        int n = Integer.parseInt(br.readLine());
        Point[] points = new Point[n];

        // n개의 점을 입력받아 Point 배열 초기화
        for (int i = 0; i < n; i++) {
            String[] line = br.readLine().split(" ");
            int x = Integer.parseInt(line[0]);
            int y = Integer.parseInt(line[1]);
            points[i] = new Point(x, y);
        }

        // PointComparator를 사용하여 Point 배열을 정렬
        Arrays.sort(points, new PointComparator());

        // 정렬된 Point 배열을 출력
        for (int i = 0; i < n; i++) {
            bw.write(points[i].x + " " + points[i].y + "\n");
        }

        // 출력 버퍼를 비우고, BufferedReader와 BufferedWriter를 닫음
        bw.flush();
        bw.close();
        br.close();
    }
}

// x, y 좌표를 가지는 Point 클래스
class Point {
    int x, y;

    // 생성자를 통해 x, y 값을 초기화
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

// Point 객체를 비교하는 PointComparator 클래스
class PointComparator implements Comparator<Point> {
    // 두 Point 객체를 비교하고, 결과를 반환하는 compare 메소드
    public int compare(Point a, Point b) {
        if (a.x == b.x) {
            return a.y - b.y;
        } else {
            return a.x - b.x;
        }
    }
}
profile
어제 보다는 내일을, 내일 보다는 오늘을 🚀

0개의 댓글