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

[java 백준]실버 1/1697번 숨바꼭질

by Meaning_ 2022. 2. 23.
728x90
반응형

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

 

1697번: 숨바꼭질

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class Main {
 
    public static int n, m;
    public static int cnt = 0;
    public static boolean[] visited = new boolean[100001];
 
    public static void BFS(int n) {
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.add(n);
 
        visited[n] = true;
        while (!queue.isEmpty()) {
            int queueSize = queue.size();
 
            for (int i = 0; i < queueSize; i++) {
                ArrayList<Integer> arr = new ArrayList<Integer>();
                int num = queue.poll();
 
                if (num == m) {
 
                    return;
                }
 
                arr.add(num * 2);
                arr.add(num + 1);
                arr.add(num - 1);
 
                for (int j = 0; j < arr.size(); j++) {
 
                    if (arr.get(j) >= 0 && arr.get(j) <= 100000) {
 
                        if (!visited[arr.get(j)]) {
                            visited[arr.get(j)] = true;
                            queue.add(arr.get(j));
                        }
 
                    }
                }
 
            }
            cnt++;
 
        }
 
    }
 
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());
 
        if (n == m) {
            System.out.println(0);
 
        } else {
            BFS(n);
            System.out.println(cnt);
        }
 
    }
 
}
cs

 

정말 오랜만에 온전히 내 힘으로 푼 문제인데 아마 밑에 너비우선탐색이라 적혀있지 않았으면 못풀었을수도 있다 ㅋㅋ

문제를 풀면서 while문으로만 컨트롤하려니까 문제가 많았는데 그냥 BFS메서드 하나 만들어줘서 거기에 BFS구현하고 num==m이면 함수 return해줄수 있게 해주니까 금방 풀렸다.

 

이런식으로 가지치기가 가능하다. 그래서 큐에 세로 한줄 씩 담아서 인접노드 탐색해주면 된다! 

빨간펜 친것 처럼 세로 한줄씩 담아주면 된다

728x90
반응형

댓글