1 minute read

๐Ÿ“Œ ๋‚œ์ด๋„

๐Ÿฅ‡ Gold 4


๐Ÿ“Œ ๋ฌธ์ œ

https://www.acmicpc.net/problem/1987

image

image


๐Ÿ“Œ BFS๋กœ ํ’€ ์ˆ˜ ์—†๋Š” ์ด์œ 

๊ฐˆ์ˆ˜ ์žˆ๋Š” ๋ฐฉํ–ฅ์ด ์ด์ „ ๋ฐฉํ–ฅ์„ ์ œ์™ธํ•˜๊ณ  ์ตœ๋Œ€ 3๋ฐฉํ–ฅ์ด๊ณ , ์•ŒํŒŒ๋ฒณ์˜ ๊ฐœ์ˆ˜์ธ 26๊ฐœ๋งŒํผ ๊นŠ๊ฒŒ ๋“ค์–ด๊ฐ„๋‹ค.
๋”ฐ๋ผ์„œ, DFS์—์„œ ๊นŠ์ด๊ฐ€ 26์ธ ์ง€์ ์˜ ๊ฐœ์ˆ˜๋งŒํผ BFS์—์„œ๋Š” Queue์— ๋‹ค์Œ ์œ„์น˜์ •๋ณด๊ฐ€ ๋“ค์–ด๊ฐ€๊ฒŒ ๋˜๋Š”๋ฐ ์ด ๊ฐ’์ด ๋‹ค์Œ ์ฝ”๋“œ์˜ ๊ฒฐ๊ณผ๊ฐ’๊ณผ ๊ฐ™๋‹ค.

public class Test {
    static final int[] DR = {-1, 0, 1, 0};
    static final int[] DC = {0, 1, 0, -1};
    static long count = 0;
    static int N = 20;
    static boolean visited[][];

    public static void main(String[] args) throws IOException {
        visited = new boolean[N][N];

        DFS(0, 0, 1);

        System.out.println(count);
    }

    static void DFS(int r, int c, int depth) {
        if (depth == 26) {
            count++;
            return;
        }

        visited[r][c] = true;

        for (int i = 0; i < DR.length; i++) {
            int nextR = DR[i] + r;
            int nextC = DC[i] + c;
            if (nextR < 0 || nextR >= N || nextC < 0 || nextC >= N) continue;

            if (!visited[nextR][nextC]) {
                DFS(nextR, nextC, depth + 1);
            }
        }

        visited[r][c] = false;
    }
}

image


๐Ÿ“Œ BFS๊ฐ€ ์‹ค์žฌ๋กœ๋Š” ๊ฐ€๋Šฅํ•œ ์ด์œ 

ํ•˜์ง€๋งŒ, ์ด์ „์— ๋‹ค๋…€์™“๋˜ ๊ณณ๋“ค์˜ ์•ŒํŒŒ๋ฒณ๋“ค๋งŒ ๋™์ผํ•˜๋‹ค๋ฉด, ์‹ฌ์ง€์–ด ๋‹ค๋…€์™“๋˜ ์ˆœ์„œ๊ฐ€ ๋‹ค๋ฅด๋”๋ผ๋„ ํ˜„์žฌ ์ง€์ ์—์„œ์˜ ๋‹ค๋…€์˜จ ์ •์ ๋“ค์˜ ์•ŒํŒŒ๋ฒณ์ด ๋™์ผํ•˜๋‹ค๋ฉด, ๊ทธ ์ง€์ ์—์„œ ์—ฌ๋Ÿฌ๋ฒˆ BFS๋ฅผ ๋Œ๋ฆด ํ•„์š”๊ฐ€ ์—†์ด ๋‹ค๋ฅธ BFS๋Š” ์ œ์™ธ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค. ( BFS์— ๋ฐฑํŠธ๋ž˜ํ‚น ์‘์šฉ )

์œ„์˜ 1๋ฒˆ ๊ทธ๋ฆผ์—์„œ G์— ๋„๋‹ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์—ฌ๋Ÿฌ๊ฐ€์ง€์ด์ง€๋งŒ, ๊ฒฐ๊ตญ G๋ผ๋Š” ์ •์ ์—์„œ ๋‹ค๋…€์˜จ ์•ŒํŒŒ๋ฒณ์€ ( A, B, C, D, E, F, G ) ์ด๋ฏ€๋กœ, ๋‹ค๋…€์˜จ ๊ฒฝ๋กœ์— ์ƒ๊ด€์—†์ด ๋™์ผํ•˜๊ฒŒ D๋กœ๋Š” ๋ชป๊ฐ€๊ณ , H์ชฝ์œผ๋กœ๋งŒ ๊ฐˆ ์ˆ˜ ์žˆ๋‹ค.

๋˜ํ•œ ์œ„์˜ 2๋ฒˆ ๊ทธ๋ฆผ์—์„œ I์— ๋„๋‹ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ์—ฌ๋Ÿฌ๊ฐ€์ง€์ด๊ณ , ์‹ฌ์ง€์–ด ๋“ค์–ด๊ฐ€๋Š” ์•ŒํŒŒ๋ฒณ์˜ ์ˆœ์„œ์กฐ์ฐจ๋„ ๋‹ค๋ฅด์ง€๋งŒ I๋ผ๋Š” ์ •์ ์— ๋„๋‹ฌํ•˜๋Š” ์ˆœ๊ฐ„, ์ด์ „์˜ ์•ŒํŒŒ๋ฒณ์ด ๋™์ผํ•˜๋‹ค๋ฉด, ๋ชจ๋‘ ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ ๋„๋‹ฌํ•œ ๊ฒƒ๊ณผ ๋งˆ์ฐฌ๊ฐ€์ง€๊ฐ€ ๋˜๊ฒŒ ๋œ๋‹ค.

๋”ฐ๋ผ์„œ, BFS์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ๊ตฌํ˜„์„ ํ•  ๋•Œ, Queue๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ, LinkedHashSet์— ( int CurR, int CurC, boolean[ ] ) ์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ ๊ตฌํ˜„์„ ํ•˜๋ฉด, ์˜คํžˆ๋ ค DFS๋กœ ๊ตฌํ˜„์„ ํ•˜๋Š” ๋ฐฉ์‹๋ณด๋‹ค๋„ ๋” ๋น ๋ฅธ ๋™์ž‘์‹œ๊ฐ„์ด ๋‚˜์˜ค๋Š” ์ฝ”๋“œ ๊ตฌํ˜„์ด ๊ฐ€๋Šฅํ•  ๊ฒƒ ๊ฐ™๋‹ค.

image



๊ฐœ์ธ ๊ณต๋ถ€ ๊ธฐ๋ก์šฉ ๋ธ”๋กœ๊ทธ์ž…๋‹ˆ๋‹ค.
ํ‹€๋ฆฌ๊ฑฐ๋‚˜ ์˜ค๋ฅ˜๊ฐ€ ์žˆ์„ ๊ฒฝ์šฐ ์ œ๋ณดํ•ด์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.๐Ÿ˜