[BOJ] 2606. 바이러스
2021. 3. 16. 14:58ㆍ알고리즘/백준 문제 풀이
https://www.acmicpc.net/problem/2606
접근 방법
전형적인 BFS ,DFS 문제이다.
1번의 컴퓨터로 바이러스가 진행이 되므로
Queue 에 1을 넣어준 후 BFS를 돌려주면 되는 문제이다.
Need Know
- BFS
전체 코드 ( Java )
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Main{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int computer;
static int count;
static boolean[][] con;
static boolean[] visit;
public static void main(String[] args) throws IOException{
set();
solve();
br.close();
bw.flush();
bw.close();
}
static void set() throws IOException {
computer = Integer.parseInt(br.readLine());
count = Integer.parseInt(br.readLine());
con = new boolean[computer+1][computer+1];
visit = new boolean[computer+1];
for(int i=0; i<count; i++){
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
con[a][b] = true;
con[b][a] = true;
}
}
static void solve() throws IOException {
bfs();
int result = 0;
for(int i=2; i<computer+1; i++){
if(visit[i]) {
result++;
}
}
bw.write(result+"");
}
static void bfs(){
Queue<Integer> queue = new LinkedList<>();
queue.add(1);
visit[1] = true;
while(!queue.isEmpty()){
int peek = queue.poll();
for(int i=0; i<computer+1; i++){
if(con[peek][i] && !visit[i]){
queue.add(i);
visit[i] = true;
}
}
}
}
}
'알고리즘 > 백준 문제 풀이' 카테고리의 다른 글
[BOJ] 2573. 빙산 (0) | 2021.03.26 |
---|---|
[BOJ] 2178. 미로 탐색 (0) | 2021.03.16 |
[BOJ] 1339. 단어 수학 (0) | 2021.03.15 |
[BOJ] 1436. 영화감독 숌 (0) | 2021.03.05 |
[BOJ] 9466. 텀 프로젝트 (0) | 2020.11.15 |