본문 바로가기
이것저것

백준 1697 숨바꼭질

by 문자메일 2018. 1. 13.

import java.util.Scanner;


public class testPorject{

static int N, K;

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

N = sc.nextInt();

K = sc.nextInt();

move(N);

sc.close();

}

private static void move(int location){

//queue에는 변동 후 위치를 저장하고, visit 배열에는 몇번째에 방문하는지를 저장한다.

int[] visit = new int[200001];

Queue queue = new Queue(200001);

visit[location] = 1;

queue.push(location);

while(!queue.isEmpty()){

int x = queue.pop();

if( x == K){

System.out.println(visit[x]-1);

}

else{

if( x-1 >= 0 && visit[x-1] == 0){

queue.push(x-1);

visit[x-1] = visit[x]+1;

}

if( x+1 <= 100000 && visit[x+1] == 0){

queue.push(x+1);

visit[x+1] = visit[x]+1;

}

if( 2*x <= 100000 && visit[x*2] == 0){

queue.push(x*2);

visit[x*2] = visit[x]+1;

}

}

}

}

}


class Queue{

private int front;

private int rear;

private int[] storage;

public Queue(int size){

storage = new int[size];

front = -1;

rear = -1;

}

//push

public void push(int x){

storage[++rear] = x;

}

//pop

public int pop(){

return storage[++front];

}

//isEmpty()

public boolean isEmpty(){

return front == rear;

}

}


댓글