1 λΆ„ μ†Œμš”

πŸ“ [S3_2606] λ°”μ΄λŸ¬μŠ€

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	static StringTokenizer st;
	static int[][] arr;
	static boolean[] isChecked;
	static int N;
	// 좜λ ₯ν•  컴퓨터 수
	static int cnt = 0;

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

		// 컴퓨터 수
		int N = Integer.parseInt(br.readLine());

		// 컴퓨터 쌍의 수
		int cp = Integer.parseInt(br.readLine());

		// 컴퓨터 쌍 μ—°κ²° μƒνƒœ λ°°μ—΄ 1-> μ—°κ²° o , 0-> μ—°κ²° x
		arr = new int[N][N];

		// 감염 유무
		isChecked = new boolean[N];

		for (int i = 0; i < cp; i++) {
			st = new StringTokenizer(br.readLine(), " ");
			int first = Integer.parseInt(st.nextToken());
			int second = Integer.parseInt(st.nextToken());

			// μˆœμ„œ 상관 x
			arr[first - 1][second - 1] = 1;
			arr[second - 1][first - 1] = 1;
		}

		// 감염 체크
		dfs(0);

		// 좜λ ₯
		sb.append(cnt);
		System.out.println(cnt);
	}

	// 감염 체크
	static void dfs(int current) {
		// 기저쑰건
		if(current == arr.length) {
			return;
		}
		// 처음 μ‹œμž‘ν•˜λŠ” μ»΄ν“¨ν„°λŠ” λ°”μ΄λŸ¬μŠ€μ— κ°μ—Όλ˜μ–΄μžˆμŒ
		isChecked[current] = true;
		
		for (int i = 0; i < arr.length; i++) { 
			// λ‹€μŒ 것이 false ( 감염 μ•ˆλ˜μ–΄ 있고 ), i κ°€ ν˜„μž¬ 값이 μ•„λ‹ˆκ³  , 간선이 μ—°κ²°λ˜μ–΄ μžˆλ‹€λ©΄ μΆ”κ°€
			if (!isChecked[i] && i != current && arr[current][i] == 1) { 
				cnt++;
				// 계속 κ°„μ„  λ”°λΌμ„œ λ“€μ–΄κ°€μ„œ νŒŒμ•…ν•œλ‹€
				dfs(i);
			}
		}
	}
}

πŸ€” λ‚˜μ˜ 생각

dfs둜 ν’€μ–΄μ£Όμ—ˆλ‹€.
1번 컴퓨터와 μ—°κ²°λ˜μ–΄μžˆλŠ” 간선을 λκΉŒμ§€ λ”°λΌκ°€μ„œ isChecked에 trueλ₯Ό μ£Όκ³  μΉ΄μš΄νŒ…μ„ ν•΄μ£Όμ—ˆλ‹€.
λ§Žμ€ μ‚¬λžŒλ“€μ΄ μžμ‹μ„ λ‘λ²ˆ μ„€μ •ν•΄μ£ΌλŠ” 것을 κΉŒλ¨Ήμ—ˆλ‹€λŠ”λ° μ—¬κΈ°μ„œλŠ” λ°©ν–₯이 μ—†κΈ° λ•Œλ¬Έμ— λ‘λ²ˆ μ„€μ •ν•΄μ£ΌλŠ” 것이 많이 놓칠 수 μžˆλŠ” 뢀뢄이닀.