본문 바로가기
알고리즘/완전탐색

[java 백준]골드 5/5014번 스타트링크

by Meaning_ 2022. 3. 21.
728x90
반응형

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

 

5014번: 스타트링크

첫째 줄에 F, S, G, U, D가 주어진다. (1 ≤ S, G ≤ F ≤ 1000000, 0 ≤ U, D ≤ 1000000) 건물은 1층부터 시작하고, 가장 높은 층은 F층이다.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
public class Main {
 
    public static class Stair {
        int std = 0;
        int cnt = 0;
 
        public Stair(int std, int cnt) {
            this.std = std;
            this.cnt = cnt;
        }
    }
 
    public static int F, S, G, U, D;
 
    public static boolean visited[];
 
    public static String BFS(int n) {
 
        Queue<Stair> queue = new LinkedList<Stair>();
 
        queue.add(new Stair(n, 0));
        visited[n] = true;
 
        while (!queue.isEmpty()) {
 
            Stair stairs = queue.poll();
            int std = stairs.std;
 
            if (std >= 1 && std <= F) {
 
                if (std == G) {
                    String ans = Integer.toString(stairs.cnt);
                    return ans;
                }
                if (std + U <= F && std + U >= 1) {
 
                    if (!visited[std + U]) {
                        visited[std + U] = true;
                        queue.add(new Stair(std + U, stairs.cnt + 1));
                    }
 
                }
 
                if (std - D >= 1 && std - D <= F) {
                    if (!visited[std - D]) {
                        visited[std - D] = true;
                        queue.add(new Stair(std - D, stairs.cnt + 1));
                    }
 
                }
            }
 
        }
        return "use the stairs";
 
    }
 
    public static void main(String[] args) throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
 
        F = sc.nextInt();
        S = sc.nextInt();
        G = sc.nextInt();
        U = sc.nextInt();
        D = sc.nextInt();
 
        visited = new boolean[F + 1];
 
        System.out.println(BFS(S));
 
    }
 
}
 
cs

 

BFS라고 풀라고 되어있어서 BFS라고 풀었닼ㅋㅋ 근데 잘 생각해보면 인접노드 탐색이니까 BFS가 맞다.

현재 있는 층에서 내려가는거 ,올라가는거(인접노드들) 를 다 큐에 넣어주면 됐다.(단 내려가거나 올라갔을 때 그 수가 1이상 F이하여야함)

 

나는 런타임에러를 계속 봤는데 그 중에서도 인덱스 범위를 넘어선다는 에러에 자꾸 걸렸다.

 

이유는 

1번/2번 둘로 나눠서 생각해줬어야했다. 

나는 if(!visited[std+U] && std+U<=F && std+U>=1) 로 세개를 다 묶어서 생각해줬는데

만약 std+U가 F를 초과해버린다면 당연히 indexOutOfBounds를 뿜어낼수 밖에 없었다.

 

 

728x90
반응형

댓글