Algorithm/백준
[백준] 13549번 숨바꼭질3
sirius
2021. 3. 11. 10:12
https://www.acmicpc.net/problem/13549
13549번: 숨바꼭질 3
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일
www.acmicpc.net
* 2 의 경우 이동 시간이 0초라서 증가하지 않으므로 다른 이동 보다 먼저 계산되어야 함
import java.util.*;
import java.io.*;
class Node {
int x;
int time;
public Node(int x, int time){
this.x = x;
this.time = time;
}
}
public class Main {
static int N, K;
static boolean[] visit = new boolean[100001];
static int time = Integer.MAX_VALUE;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
K = sc.nextInt();
if(N == K) {
System.out.println(0);
} else {
bfs();
System.out.println(time);
}
}
public static void bfs() {
Queue<Node> q = new LinkedList<>();
q.offer(new Node(N, 0));
visit[N] = true;
while(!q.isEmpty()) {
Node node = q.poll();
if(node.x == K) {
time = Math.min(time, node.time);
}
int next;
next = node.x * 2;
if(next < 100001 && !visit[next]) {
q.offer(new Node(next, node.time));
visit[next] = true;
}
next = node.x -1;
if(next >= 0 && !visit[next]) {
q.offer(new Node(next, node.time + 1));
visit[next] = true;
}
next = node.x + 1;
if(next < 100001 && !visit[next]) {
q.offer(new Node(next, node.time + 1));
visit[next] = true;
}
}
}
}