본문 바로가기
알고리즘/백준 Baekjoon

백준 1697번 숨바꼭질(JAVA) - BFS

by 꾸준함 2023. 3. 24.

백준 1697번

 

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

 

1697번: 숨바꼭질

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

www.acmicpc.net

 

 

문제설명

x+1, x-1 , x*2로 움직이는 좌표를 계산해서 BFS

 

 

접근

BFS로 접근

 

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
    static Queue<Integer> q = new LinkedList<>();
    static int[] map = new int[100001];
    static int n,m;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer tk = new StringTokenizer(br.readLine());
        n = Integer.parseInt(tk.nextToken());
        m = Integer.parseInt(tk.nextToken());

        map[n] = 1;
        q.offer(n);
        while (!q.isEmpty()) {
            int nx;
            int t = q.poll();

            if(t == m){
                System.out.println(map[t]-1);
            }

            for(int i=0;i<3;i++){
                if(i==0){
                   nx = t+1;
                }else if(i==1){
                    nx = t-1;
                }else{
                    nx = t*2;
                }

                if(nx<0 || nx > 100000 || map[nx]!=0) continue;
                q.offer(nx);
                map[nx] = map[t]+1;
            }
        }
    }

}