PS/BaekJoon

1260 JAVA DFS์™€ BFS

chaerlo127 2024. 1. 7. 15:47
728x90

๐ŸŒฑ ๋ฌธ์ œ

 

1260๋ฒˆ: DFS์™€ BFS

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ

www.acmicpc.net

 

๐ŸŒฑ ํ•ด๊ฒฐ๊ณผ์ •

1. DFS ์™€ BFS์˜ ๊ฐœ๋…์„ ๊ณต๋ถ€ํ•œ ์ดํ›„

2. ๊ทธ์— ๋งž๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ–ˆ๋‹ค.


๐ŸŒฑ DFS (๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰)

์žฌ๊ท€๋ฅผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— BFS ๋ณด๋‹ค ๋Š๋ฆฐ ๊ฒƒ์ด ํŠน์ง•

BFS์™€ ๋‹ฌ๋ฆฌ ์–ด๋–ค ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ์—ฌ๋ถ€๋ฅผ ๋ฐ˜๋“œ์‹œ ๊ฒ€์‚ฌ

์‹œ๊ฐ„ ๋ณต์žก๋„

LinkedList : O(N + E), N: ์ •์ ์ˆ˜, E: ๊ฐ„์„  ์ˆ˜

ํ–‰๋ ฌ: O(N^2)

 

 

๐ŸŒฑ BFS (๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰)

์ตœ๋‹จ ๊ฒฝ๋กœ, ์ž„์˜์˜ ๊ฒฝ๋กœ๋ฅผ ์ฐพ๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ 

์žฌ๊ท€ X, Iteration O

ํ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— FIFO (First Input First Output)

์‹œ๊ฐ„ ๋ณต์žก๋„ 

O(N^2)

 

 

๐ŸŒฑ DFS & BFS  ๋ฌธ์ œ ์ฐจ์ด์ 

DFS

๋ชจ๋“  ์นœ๊ตฌ ๊ด€๊ณ„๋ฅผ ๋‹ค ์‚ดํŽด๋ณด๋Š” ๊ฒฝ์šฐ

 

BFS

๊ณ ์ •๋œ ๊ฐ’๊ณผ ๊ฐ€๊นŒ์šด ๊ด€๊ณ„๋ถ€ํ„ฐ ํƒ์ƒ‰

 

728x90

๐ŸŒฑ ์ฝ”๋“œ

import java.io.*;
import java.util.*;
public class Main {
    static int n; // ์ •์ 
    static int m; // ๊ฐ„์„ 
    static int v; // ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ
    static int[][] arrays;
    static boolean[] visited;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        while(st.hasMoreTokens()){
            n = Integer.parseInt(st.nextToken());
            m = Integer.parseInt(st.nextToken());
            v = Integer.parseInt(st.nextToken());
        }

        arrays = new int[n + 1][n + 1];
        for (int i = 0; i < m ; i ++){
            String line = br.readLine();
            st = new StringTokenizer(line);
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            arrays[x][y] = 1;
            arrays[y][x] = 1;
        }

        visited = new boolean[n + 1];
        dfs(v);
        System.out.println();

        visited = new boolean[n + 1];
        bfs(v);
    }

    private static void dfs(int a) {
        visited[a] = true;
        System.out.print(a + " ");
        for (int i = 1; i < n + 1; i++){
            if(!visited[i] && arrays[a][i] == 1){
                dfs(i);
            }
        }
    }

    private static void bfs(int a) {
        Deque<Integer> queue = new LinkedList<>();
        queue.add(a);
        visited[a] = true;
        while(!queue.isEmpty()){
            int k = queue.remove();
            System.out.print(k + " ");
            for (int i = 1; i < n + 1; i ++){
                if(!visited[i] && arrays[k][i] == 1){
                    visited[i] = true;
                    queue.add(i);
                }
            }
        }
    }
}

 

 

728x90