티스토리 뷰

PS/boj

boj)2606 - 바이러스

kingsubin 2020. 9. 3. 13:05
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int n, m, node1, node2, cnt;
    static LinkedList<Integer>[] nodeList;
    static boolean[] visited = new boolean[101];

    public static void dfs(int node) {
        if (visited[node]) return;

        visited[node] = true;
        cnt++;

        for (int nextNode : nodeList[node]) {
            dfs(nextNode);
        }
    }

    public static void bfs(int node) {
        Queue<Integer> q = new LinkedList<>();
        q.offer(node);

        while (!q.isEmpty()) {
            node = q.poll();

            if (visited[node]) continue;

            visited[node] = true;
            cnt++;

            for (int nextNode : nodeList[node]) {
                q.offer(nextNode);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        n = Integer.parseInt(br.readLine());
        m = Integer.parseInt(br.readLine());

        nodeList = new LinkedList[n+1];
        for (int i = 0; i <= n; i++) {
            nodeList[i] = new LinkedList<Integer>();
        }

        for (int i = 0; i < m; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());

            node1 = Integer.parseInt(st.nextToken());
            node2 = Integer.parseInt(st.nextToken());

            nodeList[node1].add(node2);
            nodeList[node2].add(node1);

            Collections.sort(nodeList[node1]);
            Collections.sort(nodeList[node2]);
        }

        bfs(1);
        System.out.println(cnt-1);
    }

}

 

- 아직 완벽히 이해한건 아니고 그냥 외우듯이 해서 사용했다 ..

- 머리가 모자라면 계속 반복 ! 

 

 

1. dfs/bfs 어떤방식으로도 사용 가능하다고 생각됨

2. 입력을 받을 배열, 방문여부 체크하기위한 배열 선언

3. 순서가 안맞으니 Collections.sort 

4. 방문할때마다 cnt++ 해주는데 처음에 1도 방문하니까 1번 컴퓨터를 제외하기 위해 sout(cnt-1)


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

'PS > boj' 카테고리의 다른 글

boj)1012 - 유기농 배추  (0) 2020.09.03
boj)2667 - 단지번호붙이기  (0) 2020.09.03
boj)1260 - DFS와 BFS  (0) 2020.09.03
boj)18352 - 특정 거리의 도시 찾기  (0) 2020.09.02
boj)1459 - 걷기  (0) 2020.08.31