네트워크

function solution(n, computers) {
  // 내게 익숙한 그래프로 변환
  const graph = {};
  computers.forEach((edges, idx) => {
    graph[idx + 1] = [];
    edges.forEach((vertex, index) => {
      if (index != idx && vertex == 1) {
        graph[idx + 1].push(index + 1);
      }
    });
  });

  let count = 0;
  const stack = [];
  const visitedList = [];
  const visitedHash = {};

  // 각 노드별로 dfs돌아서 visited를 갱신하는 것이 목표
  // 한 노드에서 방문할 수 있는 곳은 다 방문하니, 네트워크 숫자를 1씩 증가
  for (const node in graph) {
    if (!visitedHash.hasOwnProperty(node)) {
      stack.push(node);
      while (stack.length) {
        const popped = stack.pop();
        visitedList.push(parseInt(popped));
        visitedHash[popped] = true;
        const neighbors = graph[popped];
        if (!neighbors.length) {
          break;
        }
        for (const vertex of neighbors) {
          if (visitedHash.hasOwnProperty(vertex)) {
            continue;
          }
          stack.push(vertex);
        }
      }
      count++;
    }
  }
  return count;
}

0개의 댓글