DFS and BFS
ํ๋ฆฐ ๋ถ๋ถ(ํ๋ฆฐ ์ด์ )
BFS์์ ํ์ฌ ๋ ธ๋์ ์ธ์ ๋ ธ๋๋ฅผ ๋ฃ์ ๋, ํ์ฌ ํ์์ ๋ฝ์ ๋ ธ๋์ ์ธ์ ๋ ธ๋๋ฅผ ๋ฃ์ด์ฃผ์ด์ผ ํ๋๋ฐ ์ฒ์ ์์ํ ๋ ธ๋์ ์ธ์ ๋ ธ๋๋ฅผ ๋ฃ์ด๋ฒ๋ ธ๋ค! ๊ทธ๋์ ์ฒซ ๋ ธ๋์ ์ธ์ ๋ ธ๋๋ง ๋ฐฉ๋ฌธํ๊ณ ํ์์ด ์ข ๋ฃ๋์๋ค!
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?