프로그래머스 - 네트워크

K PizzaCola·2021년 6월 18일
0
post-thumbnail

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

DFS나 BFS를 해서 하나의 네트워크에 대해 탐색을 끝내면 answer를 +1 한다.

import java.util.*;

class Solution {
    
    private int time;
    private int[] d;
    private int[] f;
    
    private Color[] vertexColors;
    
    public int solution(int n, int[][] computers) {
        vertexColors = new Color[n];
        d = new int[n];
        f = new int[n];
        Arrays.fill(vertexColors, Color.WHITE);
        
        time = 0;
        
        int answer = 0;
        for (int i = 0; i < n; i++) {
            if (vertexColors[i] == Color.WHITE) {
                bfs(computers, i);
                //dfs(computers, i);
                answer++;
            }
        }
        
        return answer;
    }
    
    private void bfs(int[][] graph, int s) {
        vertexColors[s] = Color.GREY;
        Queue<Integer> Q = new LinkedList<>();
        Q.add(s);
        
        while (!Q.isEmpty()) {
            Integer u = Q.poll();
            int[] edges = graph[u];
            
            for (int v = 0; v < edges.length; v++) {
                if (edges[v] > 0 && vertexColors[v] == Color.WHITE) {
                    vertexColors[v] = Color.GREY;
                    Q.add(v);
                }
            }
            
            vertexColors[u] = Color.BLACK;     
        }
    }
    
    private void dfs(int[][] graph, int u) {
        time = time + 1;
        vertexColors[u] = Color.GREY;
        d[u] = time;
        
        int[] edges = graph[u];
        for (int v = 0; v < edges.length; v++) {
            if (vertexColors[v] == Color.WHITE && edges[v] > 0) {
                dfs(graph, v);
            }
        }
        
        vertexColors[u] = Color.BLACK;
        time = time + 1;
        f[u] = time;
    }
    
    static enum Color {
        WHITE,
        GREY,
        BLACK
    }
}
profile
공부하는 개발자입니다.

0개의 댓글