2606 바이러스

DONGJIN IM·2022년 3월 8일
0

코딩 테스트

목록 보기
48/137

문제 이해

여러 개의 연결 요소가 존재한다.

이 때 1번 점과 연결된 연결 요소에 포함된 점의 개수를 구하는 문제이다.


문제 풀이

1번 요소에 대해서만 BFS 혹은 DFS를 수행한다.
이 때 방문한 점의 visit값을 true로 바꿔준다.

BFS, 혹은 DFS가 모두 수행되었다면 visit값이 true인 개수를 세면 된다.
1번 node는 원래부터 바이러스에서 감염되어 있으므로 true인 개수에서 1을 뺀 값이 정답이 될 것이다.


코드

import java.io.*;
import java.util.*;

public class Main {
	static int N,M;
	static ArrayList<Integer>[] lists;
	static boolean[] visit;
	static int ans = 0;
	
	static void dfs(int start) {
		if(visit[start]) return;
		
		visit[start] = true; 
		ans++;
         // 처음 방문한 점이므로 방문 표기
         // 연결 요소에 포함된 Node 개수 하나 증가
		for(int s:lists[start]) {
			dfs(s);
		}
	}
	
	public static void main(String[] args) {

		FastReader sc = new FastReader();
		StringBuilder sb = new StringBuilder();
		
		N = sc.nextInt();
		M = sc.nextInt();
		
		lists = new ArrayList[N+1];
		visit = new boolean[N+1];
		
		for(int i =1;i<N+1;i++) {
			lists[i] = new ArrayList<>();
		}
		
		for(int i =0;i<M;i++) {
			int tmp1 = sc.nextInt();
			int tmp2 = sc.nextInt();
			
			lists[tmp1].add(tmp2);
			lists[tmp2].add(tmp1);
		}
		
		dfs(1); // 1번 점이 start이므로 dfs(1) 수행
		System.out.println(ans - 1); // 1번 Node는 정답에서 빼줘야 함
	}
	
	static class FastReader // 빠른 입력을 위한 클래스
}

결과

profile
개념부터 확실히!

0개의 댓글

관련 채용 정보