๋ฌธ์
https://www.acmicpc.net/problem/13549
๋ด ๋ฌธ์ ํ์ด
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;
public class Main {
static Deque<int[]> que;
static int[] load = new int[100_001];
static int[] visited = new int[100_001];
static int n, k;
public static int bfs() {
while(!que.isEmpty()) {
int[] now = que.removeFirst();
int x = now[0];
int sec = now[1];
int[] cal = {x+1, x-1, x*2};
for(int i = 0; i < 3; i++) {
if(cal[i] == k) {
if(i == 2) visited[k] = Math.min(visited[k], sec);
else visited[k] = Math.min(visited[k], sec+1);
continue;
}
if(cal[i] < 0 || cal[i] >= load.length || visited[cal[i]] <= sec) continue;
if(i == 2) {
que.add(new int[]{cal[i], sec}); // ์๊ฐ์ด๋ ํ๋ ๊ฒฝ์ฐ ์ด ์ฆ๊ฐx
visited[cal[i]] = sec;
}
else {
que.add(new int[]{cal[i], sec+1}); // ๊ฑธ์ด๊ฐ ๋ 1์ด ์ฆ๊ฐ
visited[cal[i]] = sec+1;
}
}
}
return visited[k];
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(in.readLine());
n = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());;
if(n == k) System.out.println(0);
else {
load = new int[100_001];
visited = new int[100_001];
for(int i = 0; i < visited.length; i++) visited[i] = Integer.MAX_VALUE;
que = new ArrayDeque<>();
que.add(new int[]{n, 0});
System.out.println(bfs());
}
}
}
๐ BFS ๋ฌธ์
visited ๋ฐฐ์ด์ ๋ฐฉ๋ฌธ ์ฒดํฌ, ์ต์๊ฐ ์ ์ฅ์ ๋ ๊ฐ์ง ์ฉ๋๋ก ์ฌ์ฉํ์ฌ ํ์ดํ๋ค.
์๊ฐ์ด๋ํ๋ ๊ฒฝ์ฐ์๋ ์ด๋ฅผ ๋ํด์ฃผ์ง ์์์ผ ํ๋ค๋ ์ ๋ง ์ ์ ํ ์ฒ๋ฆฌํด์ฃผ๋ฉด ๋๋ ๋ฌธ์ !
๐ก ํผ๋๋ฐฑ
- ์ฒ์์ ๋จ์ํ ์๊ฐํด์ visited๋ฅผ boolean์ผ๋ก ๋ง๋ค๊ณ ,
์ฒ์์ผ๋ก ๋์์ ์ฐพ์ผ๋ฉด ๋ฐ๋ก return ํ๋๋ก ํ๋๋ฐ, ์๊ฐํด๋ณด๋ ๊ฑธ์ด๊ฐ๋์ง or ์๊ฐ์ด๋ํ๋์ง์ ๋ฐ๋ผ
๋จผ์ ๋์ฐฉํ๋๋ผ๋ ๋ ๋ง์ ์๊ฐ์ด ๊ฑธ๋ ธ์ ์ ์๋ค๋ ์ ์ ์ฒดํฌํด์ค์ผ ํ๋ค. !!
=> visted๋ฅผ intํ์ผ๋ก ๋ฐ๊พธ๊ณ , ์๋ฆฌ๋ง๋ค ์ต์ ์๊ฐ์ ๊ฐฑ์ ํด์ฃผ์ด ํด๊ฒฐํ๋ค.
'2๏ธโฃ Java > Problem Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java Algorithm] ์จ๋ฐ๊ผญ์ง 4 BOJ #13913 (0) | 2022.08.08 |
---|---|
[Java Algorithm] ๋ถ BOJ #5427 (0) | 2022.08.08 |
[Java Algorithm] ๋ฒฝ ๋ถ์๊ณ ์ด๋ํ๊ธฐ BOJ #2206 (0) | 2022.08.08 |
[Java Algorithm] ์ ๊ธฐํ ์์ BOJ #2023 (0) | 2022.08.05 |
[Java Algorithm] ํ BOJ #2493 (0) | 2022.08.05 |
๋๊ธ