Hansel
백준_1697(BFS) 본문

방문하지 않은 좌표를 BFS를 사용하여 탐색하면 된다.
한 좌표당 최대 3번의 탐색을 한다. (앞 뒤로 걷기, 순간이동)
O(3N) => O(N)
package TT7_JUL;
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 Boj_1697 {
static Queue<Integer> q;
static int[] point;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
point = new int[100001];
q = new LinkedList<>();
for (int i = 0; i < 100001; i++) point[i] = 100001;
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
point[n] = 0;
q.offer(n);
while (!q.isEmpty()) {
Integer now = q.poll();
int forward = now + 1;
int backward = now - 1;
int port = now * 2;
if (forward <= 100000) move(now, forward);
if (backward >= 0) move(now, backward);
if (port <= 100000) move(now, port);
}
System.out.println(point[k]);
}
private static void move(int now, int idx) {
if (point[idx] == 100001) {
point[idx] = point[now] + 1;
q.offer(idx);
}
}
}
'알고리즘과 자료구조 > BFS&DFS' 카테고리의 다른 글
| 백준_2644(DFS) (0) | 2022.07.02 |
|---|---|
| 백준_2667(DFS) (0) | 2022.07.02 |
| 프로그래머스_소수찾기(DFS,소수) (0) | 2022.05.28 |
| 백준_10026(BFS) (0) | 2022.05.16 |
| 프로그래머스_카카오 프렌즈 컬러링북(DFS) (0) | 2022.05.06 |