[백준 알고리즘][자바] 1085번 : 직사각형에서 탈출

[백준 알고리즘][자바] 1085번 : 직사각형에서 탈출

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

왼쪽 아래 꼭짓점은 (0, 0), 오른쪽 위 꼭짓점은 (w, h)로 이루어진 직사각형이 있습니다.

이때 임의의 한 점 (x, y)가 직사각형의 경계선까지 거리의 최솟값을 구하는 문제입니다.

각 꼭짓점은 아래의 조건을 따릅니다.

1 ≤ w, h ≤ 1,000

1 ≤ x ≤ w-1

1 ≤ y ≤ h-1

x, y, w, h는 정수

임의의 점 (x, y)는 각각 w, h보다 작은 수 이기때문에 직사각형 안에 존재하는 꼭짓점입니다.

따라서 직사각형의 경계선까지의 거리의 최솟값은 아래의 4가지 경우가 있습니다.

(임의의 점에서 십자가로 선을 그었을 때 각 변까지의 선이 최소값의 경우 4가지)

임의의 점이 x축까지 가는 거리 임의의 점이 x=h인 x절편까지 가는 거리 임의의 점이 y축까지 가는 거리 임의의 점이 y=w인 y절편까지 가는 거리

위의 4가지 경우에서 가장 작은 값이 경계선까지 가는 최소거리입니다.

package number_1085; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String xywh = br.readLine(); String[] xywh_array = xywh.split(" "); int x = Integer.parseInt(xywh_array[0]); int y = Integer.parseInt(xywh_array[1]); int w = Integer.parseInt(xywh_array[2]); // 직사작형의 가로변 int h = Integer.parseInt(xywh_array[3]); // 직사각형의 높이 // 4가지의 경우 // w-x, h-y, x, y int[] answer = {w-x, h-y, x, y}; int min = w-x; for(int i = 1 ; i < 4 ; i++) { min = Math.min(min, answer[i]); } bw.write(String.valueOf(min)); br.close(); bw.flush(); bw.close(); } }

from http://hyunipad.tistory.com/79 by ccl(A) rewrite - 2021-10-16 18:28:07