Completion over Perfection

백준 1260 - DFS와 BFS (JAVA) 본문

앨고리듬 알고리즘

백준 1260 - DFS와 BFS (JAVA)

난차차 2020. 11. 10. 10:00
반응형

백준 1260 - DFS와 BFS (JAVA)

DFS와 BFS를 한꺼번에 연습할 수 있는 좋은 문제네요.

앞으로 풀어갈 많은 DFS / BFS 문제의 초석이 될 문제이니

완벽하게 구현되도록 풀어보시면 좋겠네요.

 

www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

 

 

 

 

 

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
78
import java.util.*;
 
public class DFS_and_BFS {
 
    static int n, m, v;
    static boolean [] visits;
    static int [][] map;
    
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
        
        n = sc.nextInt(); //4
        m = sc.nextInt(); //5
        v = sc.nextInt(); //1
        visits = new boolean [n+1];
        map = new int [n+1][n+1];
        
        for(int i=1; i<=m; i++) {
            int temp1 = sc.nextInt(); //1
            int temp2 = sc.nextInt(); //2
            map[temp1][temp2] = 1;
            map[temp2][temp1] = 1;
        }
        
//        for(int i=1; i<=n; i++) { // 정상적으로 간선 입력 되었는지 확인
//            for(int j=1; j<=n; j++) {
//                System.out.print(map[i][j]+ " ");
//            }System.out.println();
//        }  
        
        dfs(v); //1
        
        System.out.println();
        
        visits = new boolean [n+1];
//        map = new int[n+1][n+1];
        
        bfs(v); //1
 
    }
    
    
    private static void dfs(int start) {
        visits[start] = true//visits[1] = true
        System.out.print(start + " ");
        for(int i=1; i<=n; i++) {
            if (map[i][start] == 1 && visits[i]==false) {
                dfs(i);
            }
        }
    }
    
    private static void bfs(int start) {
        Queue<Integer> q = new LinkedList<Integer>();
        q.offer(start); // 1 
        while(!q.isEmpty()) {
            int out = q.poll();
            visits[out= true;
            System.out.print(out + " ");
            for(int i=1; i<=n; i++) {
                if (map[i][out== 1 && visits[i] == false && i!=out) { // 2 3 4 
                    q.offer(i);
                    visits[i] = true;
//                    System.out.println(Arrays.toString(q.toArray()));
                }
            }       
        }
    }
}
 
cs

 

반응형
Comments