๐Ÿ’ป 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;
            }
        }
    }
}