[BOJ 1260] DFS์™€ BFS

 

1. ๋ฌธ์ œ : Link

dfs ์™€ bfs ๋ฌป๋Š” ๋ฌธ์ œ

 

2. ํ’€์ด

์ด์ œ ์Šฌ ๊ฐ์ด ์žกํžŒ๋‹ค (2023.04.07)

link[i][j] = link [j][i] = 1 (์—ฐ๊ฒฐ๋œ ์„ ์ด ์žˆ๋‹ค๊ณ  ํ‘œ์‹œํ•˜๋Š”๊ฒŒ ์ค‘์š”)

* E๋ฅผ ์ˆœํšŒํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹˜ !
* ์—ฐ๊ฒฐ๋œ ๊ฐ„์„  ์ค‘ ๋‹ค์Œ ์ˆซ์ž๊ฐ€ ์ž‘์€ ๊ฒƒ ๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•ด์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ

 

3. ์ฝ”๋“œ

package baekjoon;

import java.io.IOException;
import java.util.*;
public class Main {
    //ํ•จ์ˆ˜์—์„œ ์‚ฌ์šฉํ•  ๋ณ€์ˆ˜๋“ค
    static int[][] link; //๊ฐ„์„  ์—ฐ๊ฒฐ์ƒํƒœ
    static boolean[] visited; //ํ™•์ธ ์—ฌ๋ถ€
    static int V; //์ •์ ๊ฐœ์ˆ˜
    static int E; //๊ฐ„์„ ๊ฐœ์ˆ˜
    static int start; //์‹œ์ž‘์ •์ 

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        V = sc.nextInt();
        E = sc.nextInt();
        start = sc.nextInt();

        link = new int[1001][1001]; //์ขŒํ‘œ๋ฅผ ๊ทธ๋Œ€๋กœ ๋ฐ›์•„๋“ค์ด๊ธฐ ์œ„ํ•ด +1ํ•ด์„œ ์„ ์–ธ
        visited = new boolean[1001]; //์ดˆ๊ธฐ๊ฐ’ False

        //๊ฐ„์„  ์—ฐ๊ฒฐ์ƒํƒœ ์ €์žฅ
        for(int i = 0; i < E; i++) {
            int x = sc.nextInt();
            int y = sc.nextInt();

            link[x][y] = link[y][x] = 1;
        }

        dfs(start); //dfsํ˜ธ์ถœ

        visited = new boolean[1001]; //ํ™•์ธ์ƒํƒœ ์ดˆ๊ธฐํ™”
        System.out.println(); //์ค„๋ฐ”๊ฟˆ

        bfs(); //bfsํ˜ธ์ถœ
    }

    //์‹œ์ž‘์ ์„ ๋ณ€์ˆ˜๋กœ ๋ฐ›์•„ ํ™•์ธ, ์ถœ๋ ฅ ํ›„ ๋‹ค์Œ ์—ฐ๊ฒฐ์ ์„ ์ฐพ์•„ ์‹œ์ž‘์ ์„ ๋ณ€๊ฒฝํ•˜์—ฌ ์žฌํ˜ธ์ถœ
    public static void dfs(int cur) {
        visited[cur] = true;
        System.out.print(cur + " ");

        for(int j = 1; j <= V; j++) {
            if(link[cur][j] == 1 && !visited[j]) {
                dfs(j);
            }
        }
    }

    public static void bfs() {
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.offer(start);
        visited[start] = true;
        System.out.print(start + " ");

        while(!queue.isEmpty()) {
            int cur = queue.poll();

            for(int j = 1; j <= V; j++) {
                if(link[cur][j] == 1 && !visited[j]) {
                    queue.offer(j);
                    visited[j] = true;
                    System.out.print(j + " ");
                }
            }
        }
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ