๐ป Coding Problems Solving/DFS | BFS | Backtracking
[BOJ 17086] ์ด๋ชจํฐ์ฝ
Kim_dev
2023. 5. 16. 21:33
1. ๋ฌธ์ : https://www.acmicpc.net/problem/17086
2. ํ์ด
๋ฉ๋ชจ๋ฆฌ ์ด๊ณผ๊ฐ ๋์ง ์๊ฒ visited[clipboard์ ํ์ฌ ๋ณต์ฌ๋ ์ด๋ชจํฐ์ฝ ๊ฐ์][ํ์ฌ ํ๋ฉด์ ์ถ๋ ฅ๋ ์ด ์ด๋ชจํฐ์ฝ๊ฐ์] ํด์ฃผ๋ ๊ฒ ์ค์
3. ์ฝ๋
package baekjoon;
import java.util.*;
public class ์ด๋ชจํฐ์ฝ {
static boolean[][] visited = new boolean[1001][1001];//[clipboard][total]
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
bfs(s);
}
public static void bfs(int s) {
Queue<int[]> q = new LinkedList<>();
q.offer(new int[]{0, 1, 0});
visited[0][1] = true;
int clipboard;
int total;
int time;
while(!q.isEmpty()) {
int[] current = q.poll();
clipboard = current[0];
total = current[1];
time = current[2];
if(total == s) {
System.out.println(time);
return;
}
// 1. ํ๋ฉด์ ์๋ ์ด๋ชจํฐ์ฝ ํด๋ฆฝ๋ณด๋์ ์ ์ฅ
q.offer(new int[]{total, total, time + 1});
// 2. ํด๋ฆฝ๋ณด๋์ ์๋ ์ด๋ชจํฐ์ฝ ๋ถ์ฌ๋ฃ๊ธฐ.
// ํด๋ฆฝ๋ณด๋ ๋น์ด์์ง ์์์ผํ๊ณ , ๋ถ์ฌ๋ฃ์ ํ ๊ฐ์๊ฐ ์ด ๊ฐ์๋ณด๋ค ์ ์ด์ผ ํ๋ฉฐ, ์ด์ ์ ๋ฐฉ๋ฌธํ์ ์์ด์ผํจ.
if(clipboard != 0 && total + clipboard <= s && !visited[clipboard][total + clipboard]) {
q.offer(new int[]{clipboard, total + clipboard, time + 1});
visited[clipboard][total + clipboard] = true;
}
// 3. ํ๋ฉด์ ์๋ ์ด๋ชจํฐ์ฝ ์ค ํ๋ ์ญ์ .
// ์ด ๊ฐ์ 1๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ์์ผํ๊ณ , ๋ฐฉ๋ฌธํ์ ์์ด์ผํจ.
if(total >= 1 && !visited[clipboard][total - 1]) {
q.offer(new int[]{clipboard, total - 1, time + 1});
visited[clipboard][total - 1] = true;
}
}
}
}