[BaekJoon] 1085번 - 직사각형에서 탈출 [Java][C++]
[BaekJoon] 1085번 - 직사각형에서 탈출 [Java][C++]
1. 문제 풀이
현재 위치 $(x,\ y)$ 에 대해 가장 가까운 직사각형 경계선까지의 거리를 구하는 문제다.
현재 위치에서 왼쪽 경계선까지의 거리는 $x$, 오른쪽 경계선까지의 거리는 $w-x$, 윗쪽 경계선까지의 거리는 $h-y$, 아랫쪽 경계선까지의 거리는 $y$ 이다. 이들 중 최솟값이 직사각형 경계선까지의 최소 거리가 된다.
2. 코드
1. 풀이 [Java]
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)));
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
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.