한수는 지금 (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개의 길이를 서로 비교하여 최소값을 찾음.
#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";
}
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);
}
}