728x90
반응형
https://www.acmicpc.net/problem/5014
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
반응형
'알고리즘 > 완전탐색' 카테고리의 다른 글
[java 백준] 실버 2/ 6603번 로또 (0) | 2022.03.27 |
---|---|
[java 백준] 골드 4/ 1987번 알파벳 (0) | 2022.03.25 |
[java 백준] 골드 5/1759번 암호 만들기 (0) | 2022.03.17 |
[java 백준] 실버 2 / 1182번 부분수열의 합 (0) | 2022.03.06 |
[java 백준] 실버 1/2251번 물통 (0) | 2022.02.27 |
댓글