7JeY world

[백준 1697번] 숨바꼭질 / Java 본문

Programming/for coding test

[백준 1697번] 숨바꼭질 / Java

7JeY 2020. 3. 22. 12:13
반응형

[boj 1697번] 숨바꼭질

 

N : 수빈이의 위치

K : 동생의 위치

X+1 or X-1 : 걷기

X*2 : 순간이동

 

동생을 찾을 수 있는 가장 빠른 시간을 구하는 문제

 

 

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
<code>
public class Main {
    static int N, K;
    static int check[] = new int[100001];
     
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        K = Integer.parseInt(st.nextToken());
         
        bfs();
         
    }
     
    public static void bfs() {
        Queue q = new LinkedList();
         
        q.add(N);
        check[N] = 1;
         
        while(!q.isEmpty()) {
            N = q.poll();
             
            if(N == K)
                break;
             
            if(N+1 <=100000 && check[N+1] == 0) {
                q.add(N+1);
                check[N+1] = check[N]+1;
            }
             
            if(N-1 >= 0 && check[N-1] == 0) {
                q.add(N-1);
                check[N-1] = check[N]+1;
            }
             
            if(N*2 <= 100000 && check[N*2] == 0) {
                q.add(N*2);
                check[N*2] = check[N]+1;
            }
        }
        System.out.println(check[K]-1);
         
    }
}
 
</code>
반응형
Comments