DFS and BFS

ํ‹€๋ฆฐ ๋ถ€๋ถ„(ํ‹€๋ฆฐ ์ด์œ )

BFS์—์„œ ํ˜„์žฌ ๋…ธ๋“œ์˜ ์ธ์ ‘๋…ธ๋“œ๋ฅผ ๋„ฃ์„ ๋•Œ, ํ˜„์žฌ ํ์—์„œ ๋ฝ‘์€ ๋…ธ๋“œ์˜ ์ธ์ ‘๋…ธ๋“œ๋ฅผ ๋„ฃ์–ด์ฃผ์–ด์•ผ ํ•˜๋Š”๋ฐ ์ฒ˜์Œ ์‹œ์ž‘ํ•œ ๋…ธ๋“œ์˜ ์ธ์ ‘๋…ธ๋“œ๋ฅผ ๋„ฃ์–ด๋ฒ„๋ ธ๋‹ค! ๊ทธ๋ž˜์„œ ์ฒซ ๋…ธ๋“œ์˜ ์ธ์ ‘๋…ธ๋“œ๋งŒ ๋ฐฉ๋ฌธํ•˜๊ณ  ํƒ์ƒ‰์ด ์ข…๋ฃŒ๋˜์—ˆ๋‹ค!

  1. DFS

public static void dfs(int x) {
        if (c[x]) {
            return;
        }
        c[x] = true;
        System.out.print(x + " ");
        for (int y : a[x]) {
            if (c[y] == false) {
            	//c[y] = true;
                dfs(y);
            }
        }
    }

2. BFS

public static void bfs(int start) {
        Queue<Integer> q = new LinkedList<Integer>();
        q.add(start);
        c[start] = true;
        while (!q.isEmpty()) {
            int x = q.remove();
            System.out.print(x + " ");
            for (int y : a[x]) {
                if (c[y] == false) {
                    c[y] = true;
                    q.add(y);
                }
            }
        }
    }

DFS์™€ BFS ๊ตฌํ˜„์˜ ์ฐจ์ด

BFS : for(int y:a[x])๋ฌธ์œผ๋กœ ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋ฅผ ํ†ตํ•ด์„œ ์ธ์ ‘ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด true ์ฒ˜๋ฆฌํ•˜๊ณ , ํ์— ๋„ฃ๋Š”๋‹ค.

DFS : for(int y:a[x])๋ฌธ ์•ˆ์—์„œ ์žฌ๊ท€ํ˜ธ์ถœ๋งŒํ•˜๊ณ  true์ฒ˜๋ฆฌํ•˜์ง€ ์•Š๋Š”๋‹ค. ์™œ๋ƒํ•˜๋ฉด ์ด for๋ฌธ ๋‚ด์—์„œ true๋กœ ์ฒ˜๋ฆฌํ•ด๋ฒ„๋ฆฌ๋ฉด ๊ทธ ๋ฐ”๋กœ ๋ฐ‘์— ์žฌ๊ท€ํ•จ์ˆ˜ ํ˜ธ์ถœ์— ๋“ค์–ด๊ฐ€๋Š” ์ธ์ž๋Š” true๊ฐ€ ๋˜๋ฒ„๋ ค DFS๊ฐ€ ์žฌ๊ท€ํ˜ธ์ถœ๋˜์–ด๋„ ๋ฐ”๋กœ ๋ฆฌํ„ด๋˜๋ฒ„๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค!

main ํ•จ์ˆ˜ ๊ตฌํ˜„ 1. ์ธ์ ‘๋ฆฌ์ŠคํŠธ : ์ •์ˆ˜ํ˜• ArrayList ๋ฐฐ์—ด ์ƒ์„ฑ, ์ด์šฉํ•œ๋‹ค!

public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int start = sc.nextInt();
        a = (ArrayList<Integer>[]) new ArrayList[n+1];
        for (int i=1; i<=n; i++) {
            a[i] = new ArrayList<Integer>();
        }
        for (int i=0; i<m; i++) {
            int u = sc.nextInt();
            int v = sc.nextInt();
            a[u].add(v);
            a[v].add(u);
        }
        for (int i=1; i<=n; i++) {
            Collections.sort(a[i]);
        }
        c = new boolean[n+1];
        dfs(start);
        System.out.println();
        c = new boolean[n+1];
        bfs(start);
        System.out.println();
    }

Last updated

Was this helpful?