본문 바로가기

코딩테스트(백준)

[백준] 1697 - 숨바꼭질 - JAVA - 사좋배 공유

import java.util.Scanner;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {

	static int result;
	static Queue q;
	static int [] arr;
	static int N;
	static int K;
	static int min=Integer.MAX_VALUE;
	public static void main(String[] args) {
		Scanner sc= new Scanner(System.in);
		N =sc.nextInt();
		K = sc.nextInt();
		arr=new int[100005];
		q= new LinkedList();
		q.add(new data(N,0));
		arr[N]=1;
		BFS();
		System.out.println(min);
	}
	private static void BFS() {
		while(!q.isEmpty()) {
			data da=q.poll();
			int number= da.number;
			int count = da.count;
			int temp=0;
			if(number==K) {
				min=count;
				q.clear();
				return;
			}
			for(int i=0;i<3;i++) {
				if(i==0) {
					if(number+1<arr.length&&arr[number+1]==0) {
						temp = number+1;
						arr[temp]=1;
						q.add(new data(temp,count+1));
					}
				}
				if(i==1) {
					if(number-1>=0&&arr[number-1]==0) {
						temp = number-1;
						arr[temp]=1;
						q.add(new data(temp,count+1));
					}
				}
				if(i==2) {
					if(number*2<arr.length&&arr[number*2]==0) {
						temp = number*2;
						arr[temp]=1;
						q.add(new data(temp,count+1));
					}
				}
			}
		}
	}

}
class data {
	int number;
	int count;
	public data(int number,int count) {
		this.number=number;
		this.count=count;
	}
}