Java/Java 알고리즘

백준 14173번 Square Pasture JAVA 구현해보기

kimc 2022. 4. 24. 03:14

```

백준 14173번 Square Pasture JAVA 구현해보기

```

이번 글을 통해 배워갈 내용

  1.  백준 14173번 풀이

 


https://www.acmicpc.net/problem/14173

 

14173번: Square Pasture

In the example above, the first original rectangle has corners (6,6) and (8,8). The second has corners at (1,8) and (4,9). By drawing a square fence of side length 7 with corners (1,6) and (8,13), the original areas can still be enclosed; moreover, this is

www.acmicpc.net

백준 14173번  정사각형 초장(목장용지)은 

 

동물들을 기르기 위해 두 사각형 목장용지가 각 원점으로부터 작은 값 큰 값 순으로 좌표 두 개씩 주어질 때

 

해당 목장용지를 포함하는 가장 작은 정사각형 목장용지의 넓이를 구해주면 됩니다

 


30분 정도 위에 링크를 방문하셔서 풀어보시고

안 풀리시는 경우에만 아래 해답을 봐주시면 감사하겠습니다.


 

위의 사진을 보시면 감이 잡히시겠지만

X 좌표, Y 좌표의 범위가 가장 큰 값을 찾아서 제곱해주면 됩니다.

 

입력을 순차적으로 받고

가장 큰 값과 가장 작은 값의 입력 위치가 동일하기 때문에

이를 이용하면 쉽게 풀 수 있으나

 

점이 여러 개인 경우를 보고 생각해봐서

저는 풀이가 조금 길어졌습니다.

 


import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.List;

public class Main {
    static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws IOException {

        // 들판 좌표들
        List<Point> pasturePoints = new ArrayList<>();

        // pasturePoints 좌표값 입력
        // 좌표를 다 입력받을 필요는 없지만 확장성을 위해 입력받음
        for (int i = 0; i < 2; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine(), " ");
            final int x1 = Integer.parseInt(st.nextToken());
            final int y1 = Integer.parseInt(st.nextToken());
            final int x2 = Integer.parseInt(st.nextToken());
            final int y2 = Integer.parseInt(st.nextToken());
            Point pt1 = new Point(x1, y1);
            Point pt2 = new Point(x2, y2);
            Point pt3 = new Point(x1, y2);
            Point pt4 = new Point(x2, y1);
            pasturePoints.add(pt1);
            pasturePoints.add(pt2);
            pasturePoints.add(pt3);
            pasturePoints.add(pt4);
        }

        final int ptSize = pasturePoints.size()-1;
        // X 값 범위
        pasturePoints.sort(Comparator.comparing(Point::getX));
        final int xRange = (int) (pasturePoints.get(ptSize).getX() - pasturePoints.get(0).getX());
        // Y 값 범위
        pasturePoints.sort(Comparator.comparing(Point::getY));
        final int yRange = (int) (pasturePoints.get(ptSize).getY() - pasturePoints.get(0).getY());
        // 출력
        final int sqWidth = Math.max(xRange, yRange);
        System.out.print(sqWidth*sqWidth);
    }
}

//codemasterkimc.tistory.com [김씨의 코딩 스토리]

 

읽어주셔서 감사합니다

 

무엇인가 얻어가셨기를 바라며

 

오늘도 즐거운 코딩 하시길 바랍니다 ~ :)

 


 

728x90