[백준/BOJ] 1085번_직사각형에서 탈출하기 (C++/Java)

JIMIN·2023년 1월 25일

BOJ_Bronze

목록 보기
16/75

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

문제


한수는 지금 (x, y)에 있다. 직사각형은 각 변이 좌표축에 평행하고, 왼쪽 아래 꼭짓점은 (0, 0), 오른쪽 위 꼭짓점은 (w, h)에 있다. 직사각형의 경계선까지 가는 거리의 최솟값을 구하는 프로그램을 작성하시오.


입력


첫째 줄에 x, y, w, h가 주어진다.


출력


첫째 줄에 문제의 정답을 출력한다.



💻 예제 입력

6 2 10 3

💻 예제 출력

1

풀이


x에서 직사각형 왼쪽 변(x=0)에 도달하려면 x만큼의 길이가 필요하고, 직사각형 오른쪽 변(x=w)에 도달하려면 (w-x)만큼의 길이가 필요함.

y에서 직사각형 밑변(y=0)에 도달하려면 y만큼의 길이가 필요하고, 직사각형 윗변(y=h)에 도달하려면 (h-y)만큼의 길이가 필요함.

이 4개의 길이를 서로 비교하여 최소값을 찾음.


C++ 소스코드


#include <iostream>
using namespace std;

int main(void)
{
    int x, y, w, h, min;
    cin >> x >> y >> w >> h;
    
    min = (w-x) < x ? (w-x) : x;
    min = min < y ? min : y;
    min = min < (h-y) ? min : (h-y);
    
    cout << min << "\n";
}

Java 소스코드


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] s = br.readLine().split(" ");
        int x = Integer.parseInt(s[0]);
        int y = Integer.parseInt(s[1]);
        int w = Integer.parseInt(s[2]);
        int h = Integer.parseInt(s[3]);

        int min = Math.min((w-x), x);
        min = Math.min(min, y);
        min = Math.min(min, (h-y));

        System.out.println(min);
    }
}
profile
잘못된 코드나 정보가 있다면 알려주세요! 👋🏻

0개의 댓글