본문 바로가기
알고리즘/BAEKJOON

바이러스

by 현대타운301 2024. 3. 24.

 


 

문제 설명

 

 

 

입출력 예시

 

 

요약

1번 컴퓨터와 직.간접적으로 연결되어 있는 컴퓨터의 개수 구하기

 


 

풀이

 

접근 방식

1. 연결되어 있는 컴퓨터들을 이차원 배열로 표시

  → graph[row][col], graph[col][row] 모두 true로 연결됨을 표시

 

2. 방문하지 않은 컴퓨터(노드) 확인 후 방문

  → 재귀함수로 dfs 실행

 


 

코드리뷰

 

import java.util.*;

public class Main {
    static int N, M;
    static int count = 0;
    static boolean[][] graph;
    static boolean[] visited;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();	// 컴퓨터의 개수(노드)
        M = sc.nextInt();	// 서로 연결되어 있는 connection 개수(간선)
        
        graph = new boolean[N+1][N+1];	// 연결을 나타내는 그래프(1부터 체크하기 위해 N+1 만큼 선언)
        visited = new boolean[N+1];	// 연결된 컴퓨터를 확인(방문)했는지 체크하는 배열

        for(int i = 0; i < M; i++) {	// 간선의 개수만큼 연결 정보 입력
            int row = sc.nextInt();
            int col = sc.nextInt();
            graph[row][col] = true;
            graph[col][row] = true;
        }

        dfs(1);	// 재귀함수를 통한 깊이 우선 탐색(1번 컴퓨터와 연결된 컴퓨터의 개수 구하기)
        System.out.println(count-1);	// 자기 자신 제외 후 출력
        sc.close();
    }

    public static void dfs(int index) {
        count++;	// 방문과 동시에 연결된 컴퓨터의 개수 증가
        visited[index] = true;	// 재방문 방지
        for(int i = 1; i <= N; i++) {
            if(!visited[i] && graph[index][i]) {	// index에 해당하는 row에서 모든 컴퓨터에 접근해서 연결여부와 방문여부를 확인
                dfs(i);	// 연결되어 있고 방문한 적 없다면 해당 컴퓨터 방문
            }
        }
    }
    
}

 

 

 

'알고리즘 > BAEKJOON' 카테고리의 다른 글

단지번호붙이기  (0) 2024.03.24
체스판 다시 칠하기  (1) 2024.03.22
VSC 테스트 환경설정(with Java_BAEKJOON)  (0) 2024.03.13
for문 예제 (tree 모양 출력)  (0) 2023.08.29