- 분류 : DFS/BFS
- 문제 : https://www.acmicpc.net/problem/2606
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
79
80
81
82
83
84
85
|
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Computer {
int num;//컴퓨터 번호
boolean marked;//방문 여부
LinkedList<Computer> adjacent;
Computer(int num) {
this.num = num;
this.marked = false;
this.adjacent = new LinkedList<>();
}
}
class Graph {
Computer[] computers;
int count; //바이러스에 감염된 컴퓨터 수
Graph(int size) {
this.computers = new Computer[size];
for (int i = 0; i < size; i++) {
computers[i] = new Computer(i + 1);
}
count = 0;
}
void addEdge(int i1, int i2) {
Computer c1 = computers[i1 - 1];
Computer c2 = computers[i2 - 1];
if (!c1.adjacent.contains(c2)) {
c1.adjacent.add(c2);
}
if (!c2.adjacent.contains(c1)) {
c2.adjacent.add(c1);
}
}
void bfs() {
Queue<Computer> queue = new LinkedList<>();
Computer root = computers[0];
root.marked = true;
queue.add(root);
while (!queue.isEmpty()) {
Computer computer = queue.poll();
for (Computer c : computer.adjacent) {
if (c.marked == false) {
c.marked = true;
queue.add(c);
}
}
visit(computer);
}
}
void visit(Computer computer) {
if (computer.num != 1) {
count += 1;
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
sc.nextLine();
int edges = sc.nextInt();
sc.nextLine();
Graph g = new Graph(size);
for (int i = 0; i < edges; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
g.addEdge(a, b);
sc.nextLine();
}
g.bfs();
System.out.print(g.count);
}
}
|
cs |
'알고리즘 > 백준' 카테고리의 다른 글
[백준1012/java] 유기농 배추 (0) | 2023.05.12 |
---|---|
[백준2606/java] 바이러스 (0) | 2023.05.12 |
[백준/java] 1260번 - DFS와 BFS (1) | 2023.05.12 |
[백준/java] 18259번 - 큐2 (0) | 2023.05.12 |
[백준/java] 2164번 - 카드2 (0) | 2023.05.12 |