-
Notifications
You must be signed in to change notification settings - Fork 0
/
숨바꼭질 2.java
60 lines (45 loc) · 1.7 KB
/
숨바꼭질 2.java
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
import java.util.*;
import java.io.*;
public class Main {
static int answer;
static int answer2;
static int[] visited;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
visited = new int[100002];
Arrays.fill(visited, Integer.MAX_VALUE);
bfs(N, K);
System.out.println(answer);
System.out.println(answer2);
}
static void bfs(int start, int target) {
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
visited[start] = 0;
answer = Integer.MAX_VALUE;
answer2 = 0;
while (!queue.isEmpty()) {
int current = queue.poll();
int currentCount = visited[current];
if (current == target) {
if (currentCount < answer) {
answer = currentCount;
answer2 = 1;
} else if (currentCount == answer) {
answer2++;
}
continue;
}
int[] nextStates = {current + 1, current - 1, current * 2};
for (int next : nextStates) {
if (next >= 0 && next < visited.length && visited[next] > currentCount) {
visited[next] = currentCount + 1;
queue.add(next);
}
}
}
}
}