325. 네트워크

아현·2021년 11월 10일
0

Algorithm

목록 보기
349/400
post-custom-banner



1. Python


def solution(n, computers):               
                
    answer = 0
    visited = [0 for i in range(n)]
    
    def dfs(x):
        visited[x] = 1
        for i in range(n):
            if computers[x][i] and not visited[i]:
                dfs(i)   
    
    
    for i in range(n):
        if not visited[i]:
            dfs(i)
            answer += 1
        
    return answer



2. C++


#include <string>
#include <vector>

using namespace std;

void dfs(vector<int> &visit, int x, int n, const vector<vector<int>> &computers){
    visit[x] = 1;
    for (int i = 0; i < n; i++){
        if (computers[x][i] && !visit[i]) dfs(visit, i, n, computers);
    }
}

int solution(int n, vector<vector<int>> computers) {
    int answer = 0;
    vector<int> visit(n);
    for (int i = 0; i < n; i++){
        if (!visit[i]){
            dfs(visit, i, n, computers);
            answer++;
        }
    }
    
    return answer;
}




3. JavaScript



function solution(n, computers) {
    var answer = 0;
    let visit = Array.from({length: n},() => 0);
    function dfs(x){
        visit[x] = 1;
        for (let i = 0; i < n; i++){
            if(computers[x][i] && !visit[i]) dfs(i);
        }
        
    }
    
    for (let i = 0; i < n; i++){
        if (!visit[i]){
            dfs(i);
            answer++;
        }
    }
    return answer;
}
profile
For the sake of someone who studies computer science
post-custom-banner

0개의 댓글