[백준] 1697번 : 숨바꼭질 - Java(자바)

강재원·2022년 12월 1일
0

[코딩테스트] Java

목록 보기
195/200



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

import java.util.*;

public class Main {
    static int check[];
    static int n,k;
    
    static void bfs(int a){
        Queue<int[]> q=new LinkedList<>();
        q.add(new int[]{a,0});
        check[a]=1;
        
        while(!q.isEmpty()){
            int v[]=q.poll();
            
            if(v[0]==k){
                System.out.print(v[1]);
                return;
            }
            if(2*v[0]<=100000 && check[2*v[0]]==0){
                check[2*v[0]]=1;
                q.add(new int[]{2*v[0],v[1]+1});
            }
            if(v[0]+1<=100000 && check[v[0]+1]==0){
                check[v[0]+1]=1;
                q.add(new int[]{v[0]+1,v[1]+1});
            }
            if(v[0]-1>=0 && check[v[0]-1]==0){
                check[v[0]-1]=1;
                q.add(new int[]{v[0]-1,v[1]+1});
            }
            
        }
    }
    
    public static void main(String args[]) {
        Scanner s=new Scanner(System.in);
        n=s.nextInt();
        k=s.nextInt();
        check=new int[100001];
        bfs(n);
    }
}
profile
개념정리 & 문법 정리 & 알고리즘 공부

0개의 댓글