Home 프로그래머스(네트워크)
Post
Cancel

프로그래머스(네트워크)

첫 시도

  • dfs를 이용하여 연결된 네트워크를 전부 순회, 순회되지 않은 네트위크를 발견할 때 마다 answer 증가
  • check를 만들어 이미 방문한 네트워크인지 확인 & i와 j가 같으면 본인 네트워크이므로 다를때만 통과
  • n이 200이라 n^3까지 가능
  • 간단한 dfs문제

해결

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class Solution {
    int[][] computers;
    boolean[] check;
    int n;
    boolean[] dfs(int i) {
        check[i] = true;
        for (int j = 0; j < n; j++) {
            if (i != j && computers[i][j] == 1 && check[j] == false) {
                check = dfs(j);
            }
        }
        return check;
    }


    public int solution(int n, int[][] computers) {
        int answer = 0;
        this.computers = computers;
        this.n = n;
        check = new boolean[n];
        System.out.println(n);
        for (int i = 0; i < n; i++) {
            if (!check[i]) {
                dfs(i);
                answer++;
            }
        }
        return answer;
    }


}


참고

This post is licensed under CC BY 4.0 by the author.