Post

[BaekJoon] #1085 - 직사각형에서 탈출 [Java][C++]

[BaekJoon] #1085 - 직사각형에서 탈출 [Java][C++]

문제 링크


1. 아이디어

현재 위치 $(x,\ y)$에 대해 가장 가까운 직사각형 경계선까지의 거리를 구하는 문제다.

왼쪽 아래 꼭짓점은 $(0,\ 0)$, 오른쪽 위 꼭짓점은 $(w,\ h)$에 있으므로, 현재 위치에서 왼쪽 경계선까지의 거리는 $x$, 오른쪽 경계선까지의 거리는 $w - x$, 위쪽 경계선까지의 거리는 $h - y$, 아래쪽 경계선까지의 거리는 $y$이다. 이들 중 최솟값이 직사각형 경계선까지의 최소 거리가 된다.


2. 복잡도

접근시간공간
풀이$O(1)$$O(1)$

3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int x = Integer.parseInt(st.nextToken());
        int y = Integer.parseInt(st.nextToken());
        int w = Integer.parseInt(st.nextToken());
        int h = Integer.parseInt(st.nextToken());

        System.out.println(Math.min(Math.min(x, w - x), Math.min(y, h - y)));
    }
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int x, y, w, h;
    cin >> x >> y >> w >> h;
    cout << min({x, w - x, y, h - y});
}

This post is licensed under CC BY 4.0 by the author.