https://school.programmers.co.kr/learn/courses/30/lessons/43162

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 풀이 (JAVA)

import java.util.*;

class Solution {
    static List<ArrayList<Integer>> graph = new ArrayList<>(); // 인접리스트(그래프)
    static boolean [] visited; // 방문여부
    public int solution(int n, int[][] computers) {
        int answer = 0;
        
        visited = new boolean[n];
        for(int i=0; i<n; i++){
            graph.add(new ArrayList<Integer>()); // 인접리스트 생성
        }
        for(int i=0; i<computers.length; i++){
            for(int j=0; j<computers[i].length; j++){
                if(i != j && computers[i][j]==1){
                    graph.get(i).add(j); //인접리스트(그래프 변수 삽입)
                }
            }
        }
        
        // DFS 반복
        for(int i=0; i<n; i++){
            if(visited[i] == false){
                dfs(i);
                answer++; // 네트워크 개수 카운트 증가
            }
        }
        
        
        return answer;
    }
    // DFS 함수
    public static void dfs(int N){
        visited[N] = true;
        for(Integer next : graph.get(N)){
            if(visited[next] == false){
                visited[next] = true;
                dfs(next);
            }
        }
    }
}

 

결론

: 해당 문제는 인접리스트(그래프)와 DFS를 사용하여 네트워크에 연결된 개수를 구하는 문제이다. 인접리스트 공식과 문제의 접근을 DFS 문제로 접근 할 수 있다면 어렵지 않은 문제이다.

'프로그래머스(JAVA)' 카테고리의 다른 글

게임 맵 최단거리(BFS)  (0) 2023.04.23
성격 유형 검사하기  (0) 2023.01.15
체육복  (3) 2022.07.18
K번째 수  (0) 2022.07.18
구명 보트  (0) 2022.07.16

+ Recent posts