자바생
article thumbnail
Published 2020. 11. 11. 22:33
자바(백준) 2606 바이러스 BOJ(Java)
728x90
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
import java.io.*;
import java.util.*;
 
public class Main {
    static boolean[] visit;
    static ArrayList<Integer> [] ad;
    static int nV, nE;
    static Queue<Integer> Q;
    public static void main(String []args) throws IOException{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = new StringTokenizer(br.readLine());
 
            nV = Integer.parseInt(st.nextToken());
 
            st = new StringTokenizer(br.readLine());
 
            nE = Integer.parseInt(st.nextToken());
 
            visit = new boolean[nV+1];
            ad = new ArrayList[nV+1];
 
            for(int i = 1; i <= nV; i++)
                ad[i] = new ArrayList<>();
 
            for(int i = 0; i < nE; i++){
                st = new StringTokenizer(br.readLine());
                int t1 = Integer.parseInt(st.nextToken());
                int t2 = Integer.parseInt(st.nextToken());
 
                ad[t1].add(t2);
                ad[t2].add(t1);
            }
            System.out.print(bfs(1));
 
        }
 
        public static int bfs(int start){
            int cnt = 0;
            Q = new LinkedList<>();
            Q.add(start);
            visit[start] = true;
            while(!Q.isEmpty()){
                int element = Q.poll();
                for(int index : ad[element]){
                    if(!visit[index]){
                        Q.add(index);
                        visit[index] = true;
                        cnt++;
                    }
                }
            }
            return cnt;
        }
    }
 
 
cs

바이러스 문제는 저번에 DFS를 공부하면서 풀어보았던 문제이다. 하지만 DFS로 풀지 않고 이번에는 BFS로 풀어보았다. 

 

궁금한 점은 BFS가 DFS보다 빠르다고 생각했는데 막상 시간을 보니, 비슷한거 같아 아직 N의 크기가 많이 크지 않아 차이가 별로 안나는 것인가 했다. 아래가 DFS로 푼 것이고, 위에 부분이 BFS로 푼 것이다.

728x90

'BOJ(Java)' 카테고리의 다른 글

자바(백준) 1260 DFS와 BFS  (0) 2020.11.12
자바(백준) 1012 유기농 배추  (0) 2020.11.11
자바(백준) 2468 안전 영역  (0) 2020.11.07
자바(백준) 2667 단지번호 붙이기  (0) 2020.11.05
자바(백준) 2583 영역 구하기  (0) 2020.11.04
profile

자바생

@자바생

틀린 부분이 있다면 댓글 부탁드립니다~😀

검색 태그