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

똔의 기록·2022년 6월 8일
0

JavaScript

목록 보기
10/14
post-thumbnail

연결된 경로를 묻는 문제이기 때문에 dfs로 풀이!
javascript의 dfs는 더 직관적인 것 같다.

방문한 노드는 1로 바꾸어 재귀함수로 연결된 모든 곳을 탐색하고 나서 네트워크 갯수를 하나씩 늘려가는 방식이다.

function solution(n, computers) {
    let answer = 0;
    
    // visited arr 생성 및 초기화
    const visited = Array.from({length: n}, () => 0);
    
    // 경로 탐색이기 때문에 dfs로 풀이
    const dfs = (node) =>{
        visited[node] = 1;
        for(let i=0; i<n; i++){
            if(computers[node][i]===1 && !visited[i]){
                dfs(i);
            }
        }
    }
    
    for(let i=0; i<n; i++){
        if(!visited[i]){
            dfs(i);
            answer++;
        }
    }
    
    return answer;
}
profile
Keep going and level up !

0개의 댓글