본문 바로가기
Algorithm/Baekjoon

[백준] 1085번 : 직사각형에서 탈출 - Java

by unknownomad 2022. 3. 30.

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

 

1085번: 직사각형에서 탈출

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

www.acmicpc.net



알고리즘

직사각형의 경계선까지 가는 거리의 최솟값

  • (x,y) 위치 기준으로 상, 하, 좌, 우 중 최소값 구하기


풀이

1. Scanner

import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
    
        Scanner in = new Scanner(System.in);
        
        int x = in.nextInt();
        int y = in.nextInt();
        int w = in.nextInt();
        int h = in.nextInt();
        
        int x_min = Math.min(x, w-x); //x축 최소 거리
        int y_min = Math.min(y, h-y); //y축 최소 거리
        
        //x, y 값 중 가장 작은 값(최소 거리)
        System.out.println(Math.min(x_min, y_min));
    }
}

 

2. BufferedReader

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.StringTokenizer;
 
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());
        
        int x_min = Math.min(x, w-x); //x축 최소 거리
        int y_min = Math.min(y, h-y); //y축 최소 거리

        //x, y 값 중 가장 작은 값(최소 거리)
        System.out.println(Math.min(x_min, y_min));
    }
}

성능

  • BufferedReader > Scanner

 


출처 : https://st-lab.tistory.com/86

댓글