[프로그래머스/Level3] 네트워크

SeokHyun·2022년 7월 2일
0

프로그래머스

목록 보기
11/32

문제 링크: https://programmers.co.kr/learn/courses/30/lessons/43162

문제 접근

딱 보자마자 "이건 DFS로 접근하는 문제다"라고 생각이 들꺼다.
그 다음은 분리되어 있는 그룹의 갯수를 카운팅하는 법을 생각했다.
-> 0번부터 돌고 그 다음은 다음 루트 노드를 찾아서 또 돌면서 갯수를 증가시키면 된다.

소스 코드

import java.util.Stack;

class Solution {
    public int solution(int n, int[][] computers) {
        int count = 0;
        boolean[] visit = new boolean[n];
        Stack<Integer> stack = new Stack<>();
        
        int curNode;
        int[] connectInfo;
        while ((curNode = findNextRootIndex(visit)) > -1) {
            stack.push(curNode);
            
            while (!stack.isEmpty()) {
                curNode = stack.pop();
                visit[curNode] = true;
                connectInfo = computers[curNode];
                
                for (int i = 0; i < connectInfo.length; i++) {
                    if (i != curNode && connectInfo[i] == 1 && !visit[i]) {
                        stack.push(i);
                    }
                }
            }
            
            count++;
        }
        
        
        return count;
    }
    
    public int findNextRootIndex(boolean[] visit) {
        for (int i = 0; i < visit.length; i++) {
            if (!visit[i]) {
                return i;
            }
        }
        
        return -1;
    }
}
profile
SI를 넘어 백엔드 엔지니어를 향하여

0개의 댓글