본문 바로가기
C#/백준 알고리즘

2022.01.26 [백준] C# 직사각형에서 탈출

by ian's coding 2022. 1. 26.
728x90
반응형

 

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

 

1085번: 직사각형에서 탈출

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

www.acmicpc.net

 


풀이

 

- 정답코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
class Program{
    
    static int ShortestDistance(int x,int y,int w, int h){
        int min=x;
        if(w-x<min){
            min=w-x;
        }
        if(y<min){
            min=y;
        }
        if(h-y<min){
            min=h-y;
        }
        return min;
    }
    
    static void Main(){
        string[] s = Console.ReadLine().Split();
        int x = int.Parse(s[0]);
        int y = int.Parse(s[1]);
        int w = int.Parse(s[2]);
        int h = int.Parse(s[3]);
        Console.Write(ShortestDistance(x,y,w,h));
    }
}
cs

 

 

-처음 작성했는데 왜 틀린지 모르는 코드....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;
class Program{
    
    static int ShortestDistance(int x,int y,int w, int h){
        int minW=0;
        int minH=0;
        if(x<w-x){
            minW=x;
        }else{
            minW=w-x;
        }
        
        if(y<h-y){
            minH=h;
        }else{
            minH=h-y;
        }
        
        if(minW<minH){
            return minW;
        }else{
            return minH;
        }
    }
    
    static void Main(){
        string[] s = Console.ReadLine().Split();
        int x = int.Parse(s[0]);
        int y = int.Parse(s[1]);
        int w = int.Parse(s[2]);
        int h = int.Parse(s[3]);
        Console.Write(ShortestDistance(x,y,w,h));
    }
}
cs

위 코드는 처음 작성했는데 결과가 틀렸다고 나왔다. 하지만 왜 틀린지 모르겠다... 아시는분 댓글로 알려주세요...

 

728x90
반응형

댓글