문제 제목 : 바이러스
난이도 : 하
문제 유형 : DFS, BFS
추천 풀이 시간 : 30분 (못하면 2배 60분)
https://www.acmicpc.net/problem/2606
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어
www.acmicpc.net
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static int pcCnt;
public static int connCnt;
public static ArrayList<ArrayList<Integer>> adjList = new ArrayList<>();
public static boolean[] visited = new boolean[101];
public static int resulCnt;
public static void addEdge(int n, int m) {
adjList.get(n).add(m);
}
public static void bfs(int pc) {
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(pc);
visited[pc] = true;
while (!queue.isEmpty()) {
int now = queue.poll();
resulCnt++;
for (int i = 0; i < adjList.get(now).size(); i++) {
int adjNode = adjList.get(now).get(i);
if (!visited[adjNode]) {
queue.offer(adjNode);
visited[adjNode] = true;
}
}
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
pcCnt = sc.nextInt();
connCnt = sc.nextInt();
for (int i = 0; i < pcCnt + 1; i++) {
adjList.add(new ArrayList<Integer>());
}
for (int i = 0; i < connCnt; i++) {
int pc1 = sc.nextInt();
int pc2 = sc.nextInt();
addEdge(pc1, pc2);
addEdge(pc2, pc1);
}
bfs(1);
System.out.println(resulCnt - 1);
}
}
'Algorithm > BAEKJOON' 카테고리의 다른 글
[알고리즘-DFS,BFS] 효율적인 해킹 (0) | 2023.01.24 |
---|---|
[알고리즘-DFS,BFS] 유기농 배추 (0) | 2023.01.24 |
[알고리즘-BFS] 숨바꼭질 (0) | 2023.01.24 |
[알고리즘-DFS,BFS] DFS와 BFS (0) | 2023.01.23 |
[알고리즘-DP] 가장 높은 탑 쌓기 (0) | 2023.01.23 |