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

YunJeong Goo·2020년 11월 5일
0

프로그래머스

목록 보기
2/4

문제

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

풀이

class Node {
    constructor(index, children){
        this.visit = false;
        this.index = index;
        this.children = children;
    }
}

function solution(n, computers) {
    const nodes = [];
    computers.forEach((computer, index) => {
      const children = [];
      computer.forEach((child,i) => {
          if (index !== i && child === 1) {
              children.push(i);
          }
      });
      
      nodes.push(new Node(index, children));
    });
    
    let networkCount = 0;
    nodes.forEach(node => {
        node.children.forEach(c => {
            if (!nodes[c].visit) {
                visit(nodes[c]); 
                networkCount++;
            }
        });
        if (!node.visit && node.children.length === 0) {
            networkCount++;
        }
    });
    
    function visit(node) {
        if (node.visit) {
            return;
        }

        if (node.children.length === 0) {
            return;
        }

        node.visit = true;
        node.children.forEach(c => {
            visit(nodes[c]);
        });
    }
    
    return networkCount;
}

처음엔 Node class를 만들어서 풀었다.
visit와 children을 관리하기 위해서였다.
Node 대신에, visit을 관리하는 array를 만들어 아래와 같이 수정했다.

function solution(n, computers) {
    let networkCount = 0;
    const visit = Array.from({length : n}, () => false);
    
    computers.forEach((computer, index) => {
        computer.forEach((c,i) => {
            if (c === 1) {
                networkCount += dfs(i);
            }
        })
    });
    
    return networkCount;
    
    function dfs(computer) {
        if (visit[computer]) {
            return 0;
        } else {
            visit[computer] = true;
        }

        computers[computer].forEach((c,i) => {
            if (c === 1) {
                dfs(i);
            }
        });
        
        return 1;
    }
}

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN