슈콩

[BOJ] 1697 숨바꼭질 본문

Algorithms/Baekjoon

[BOJ] 1697 숨바꼭질

shukong 2026. 1. 28. 21:37

[문제]

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

 

 

[소스 코드]

import java.util.*;
import java.io.*;

public class Solution {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		int k = Integer.parseInt(st.nextToken());
		int[] diff = new int[200001];
		Arrays.fill(diff, -1);
		Queue<int[]> q = new LinkedList<>();
		q.offer(new int[]{n,0});
		while(!q.isEmpty()) {
			int[] curr = q.poll();
			if(curr[0]==k) {
				System.out.println(curr[1]);
				return;
			}
			if(curr[0]-1>=0 && diff[curr[0]-1]==-1) {
				q.offer(new int[] {curr[0]-1,curr[1]+1});
				diff[curr[0]-1] = curr[1] + 1;
			}
			if(curr[0]+1<=200000 && diff[curr[0]+1]==-1) {
				q.offer(new int[] {curr[0]+1,curr[1]+1});
				diff[curr[0]+1] = curr[1] + 1;
			}
			if(curr[0]*2<=200000 && diff[curr[0]*2]==-1) {
				q.offer(new int[] {curr[0]*2,curr[1]+1});
				diff[curr[0]*2] = curr[1] + 1;
			}
		}
	}
}

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 2468 안전 영역  (0) 2026.02.09
[BOJ] 5014 스타트링크  (0) 2026.02.02
[BOJ] 7569 토마토  (0) 2026.01.26
[BOJ] 2664 촌수계산  (0) 2026.01.22
[BOJ] 2667 단지번호붙이기  (0) 2026.01.22