1085: 직사각형에서 탈출

Jimin·2022년 12월 8일
0

알고리즘

목록 보기
37/71

문제

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


입력

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


출력

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


코드

#include <iostream>
#include <string.h>
#include <algorithm>
#include <utility>
#include <math.h>
#include <stdlib.h>

using namespace std;

int check(int x, int y, int w, int h);


int main() {
    int x, y, w, h; // (x, y) .  (w, y)
    scanf("%d %d %d %d", &x, &y, &w, &h);

    int L=0, L2=0, ans;

    if(check(x, y, w, h) == 1 ) {
        ans = sqrt((x-w)*(x-w) + (y-h)*(y-h));
    }
    else if(check(x, y, w, h) == 2) {
        ans = sqrt((x-0)*(x-0) + (y-h)*(y-h));
    }
    else if(check(x, y, w, h) == 3) {
        ans = sqrt((x-0)*(x-0) + (y-0)*(y-0));
    }
    else if(check(x, y, w, h) == 4) {
        ans = sqrt((x-w)*(x-w) + (y-0)*(y-0));
    }
    else {
        L = min(abs(x-w), abs(x-0));
        L2 = min(abs(y - 0), abs(y-h));
        ans = min(L, L2);
    }
    
    cout << ans;

    return 0;
}

int check(int x, int y, int w, int h) {
    if(x < 0) {
        if(y < 0) {
            return 3;
        }
        else if(y > h) {
            return 2;
        }
    }
    else if(x > w) {
        if(y > h) {
            return 1;
        }
        else if(y < 0) {
            return 4;
        }
    }
    return 5;
}
profile
https://github.com/Dingadung

0개의 댓글