엄지월드

백준 11651 좌표 정렬하기 2 본문

알고리즘

백준 11651 좌표 정렬하기 2

킨글 2024. 4. 7. 22:34
반응형

문제

방법

Collections.sort를 이용해서 정렬을 진행하였다. 

정렬을 진행할 시 조건을 정해주기 위해 implements Comparable<Coordinate>을 활용하였다.

Comparable의 조건은 y가 같을 때에 원래 x 값이 비교하려는 x값과 작을 수록 앞에 위치하도록 하였다. 

 

 

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

// 11651
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        final int loop = Integer.parseInt(br.readLine());
        List<Coordinate> list = new ArrayList<>(loop);
        for (int i = 0; i < loop; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            list.add(new Coordinate(x, y));
        }

        Collections.sort(list);
        for (Coordinate item : list) {
            System.out.println(item.getX() + " " + item.getY());
        }
    }

    private static class Coordinate implements Comparable<Coordinate>{
        private int x;
        private int y;

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

        public int getX() {
            return x;
        }

        public void setX(int x) {
            this.x = x;
        }

        public int getY() {
            return y;
        }

        public void setY(int y) {
            this.y = y;
        }

        @Override
        public int compareTo(Coordinate o) {
            if(this.y == o.y) {
                return this.x - o.x;
            } else {
                return this.y - o.y;
            }
        }
    }
}

'알고리즘' 카테고리의 다른 글

백준 2167 2차원 배열의 합  (0) 2024.04.08
백준 11004 K번째 수  (0) 2024.04.07
백준 7785 회사에 있는 사람  (0) 2024.04.03
백준 2960 반례  (0) 2023.01.24
Oracle - 동명 동물 수 찾기 59041  (0) 2022.10.10
Comments