[백준 1260] DFS와 BFS - 인접 리스트 이용
Algorithm/백준(BOJ)

[백준 1260] DFS와 BFS - 인접 리스트 이용

반응형

[백준 1260] DFS와 BFS


문제 출처 : https://www.acmicpc.net/problem/1260









1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
public class Main {
    
    public static void dfs(ArrayList[] a, boolean[] c, int v) {
        
        if(c[v]) return;
        
        c[v] = true;
        System.out.print(v + " ");
        
        for (int vv : a[v]) {
            if(!c[vv]) {
                dfs(a,c,vv);
            }
        }
    }
    
    public static void bfs(ArrayList[] a, boolean[] c, int v) {
        Queue q = new LinkedList<>();
        
        q.add(v);
        c[v] = true;
        
        while(!q.isEmpty()) {
            v = q.poll();
            System.out.print(v + " ");
            
            for(int vv : a[v]) {
                if(!c[vv]) {
                    q.add(vv);
                    c[vv] = true;
                }
            }
        }
        
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        int m = sc.nextInt();
        int v = sc.nextInt();
        
        ArrayList[] a = (ArrayList[]) new ArrayList[n+1];
        
        for (int i = 0; i <= n; i++) {
            a[i] = new ArrayList<>();
        }
        
        boolean[] c = new boolean[n+1];
        
        for (int i = 0; i < m; i++) {
            int v1 = sc.nextInt();
            int v2 = sc.nextInt();
            
            a[v1].add(v2);
            a[v2].add(v1);
        }
        
        for (int i = 1; i <= n; i++) {
            Collections.sort(a[i]);
        }
        
        dfs(a, c, v);
        System.out.println();
        Arrays.fill(c, false);
        bfs(a, c, v);
    }
 
}
cs


반응형

'Algorithm > 백준(BOJ)' 카테고리의 다른 글

[백준 10819] 차이를 최대로  (0) 2019.01.20
[백준 1182] 부분집합의 합  (1) 2019.01.17
[백준 1018] 체스판 다시 칠하기  (2) 2019.01.10
[백준 2805] 나무 자르기  (0) 2018.06.09
[백준 1931] 회의실 배정  (6) 2018.06.02