백준 1697번 숨바꼭질

하우르·2021년 3월 18일
0
post-custom-banner
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
	static final int MAX = 100000;

	static class Location {
		int n, distance;

		public Location(int n, int distance) {
			this.n = n;
			this.distance = distance;
		}
	}

	public static int BFS(int start_point, int last_point) {
		boolean[] visited = new boolean[MAX + 1];
		Queue<Location> will_visit = new LinkedList<Location>();
		Location start = new Location(start_point, 0);
		will_visit.add(start);
		while (will_visit.size() > 0) {
			Location current_point = will_visit.remove();
			if (current_point.n == last_point)
				return current_point.distance;
			if (current_point.n < 0 || current_point.n > MAX)
				continue;
			if (visited[current_point.n])
				continue;
			visited[current_point.n] = true;

			will_visit.add(new Location(current_point.n - 1, current_point.distance + 1));
			will_visit.add(new Location(current_point.n + 1, current_point.distance + 1));
			will_visit.add(new Location(current_point.n * 2, current_point.distance + 1));
		}
		return 0;
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int K = Integer.parseInt(st.nextToken());
		int N = Integer.parseInt(st.nextToken());
		int count = BFS(K, N);
		System.out.print(count);

	}

}
profile
주니어 개발자
post-custom-banner

0개의 댓글