๐Ÿ’ก Algorithm

[Java] DFS์™€ BFS (Lv. Sliver2)

jcowwk 2025. 2. 19. 10:47

DFS์™€ BFS (Lv. Sliver2)


1. ๋ฌธ์ œ

2. ํ’€์ด


1. ๋ฌธ์ œ

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

 

2. ํ’€์ด

import java.util.*;
import java.io.*;

class Main {
    static int[][] graph;
    static boolean[] visited;
    
    public static void dfs(int V) {
        visited[V] = true;
        System.out.print(V + " ");
        
        if (V == graph.length) {
            return;
        }
        
        for (int i = 1; i < graph.length; i++) {
            if (graph[V][i] == 1 && visited[i] == false) {
                dfs(i);
            }
        }
    }
    
    public static void bfs(int V) {
        Queue<Integer> q = new LinkedList<>();
        
        q.add(V);
        visited[V] = true;
        System.out.print(V + " ");

        while (!q.isEmpty()) {
            int tmp = q.poll();
            
            for (int i = 1; i < graph.length; i++) {
                if (graph[tmp][i] == 1 && visited[i] == false) {
                    q.add(i);
                    visited[i] = true;
                    System.out.print(i + " ");
                }
            }
        }
    }
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        int V = Integer.parseInt(st.nextToken());
        
        graph = new int[N+1][N+1];
        
        for (int i = 0; i < M; i++) {
            st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            graph[u][v] = graph[v][u] = 1;
        }
        
        visited = new boolean[N+1];
        dfs(V);
        
        System.out.println();
        
        visited = new boolean[N+1];
        bfs(V);
    }
}

 

 

์œ„์˜ ์ฝ”๋“œ๋กœ ์œ„์™€ ๊ฐ™์€ ํ˜•ํƒœ์˜ ํŠธ๋ฆฌ๊ฐ€ ์กด์žฌํ•  ๋•Œ DFS์™€ BFS ํƒ์ƒ‰ ๋ฐฉ์‹์„ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

- DFS

ํ˜„์žฌ ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ ์ค‘ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.

1 -> 2 -> 4 -> 3 -> 5 ์˜ ์ˆœ์„œ๋กœ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.

 

- BFS

์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ํ™œ์šฉํ•ด์„œ ๊ฐ€๊นŒ์šด ๋…ธ๋“œ ์ˆœ์„œ๋Œ€๋กœ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.

1 -> 2 -> 3 -> 4 -> 5 ์˜ ์ˆœ์„œ๋กœ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.


๋ฌธ์ œ๊ฐ€ ์žˆ์œผ๋ฉด ๋Œ“๊ธ€ ๋‚จ๊ฒจ์ฃผ์„ธ์š” !

ํ”ผ๋“œ๋ฐฑ์€ ์–ธ์ œ๋‚˜ ํ™˜์˜์ž…๋‹ˆ๋‹ค <3