LoginSignup
2
2

More than 1 year has passed since last update.

グラフの連結成分(JavaScript版)

Last updated at Posted at 2016-01-06

こんにちは。
グラフの連結成分」を求めるコードを JavaScript で書いてみました。
graph.jpg

$ js connected_components.js
[[ 0,1,2,3,4,6 ], [ 5,7 ]]
connected_components.js
const graph = {"0": ["1", "2", "3"], "1": ["2"], "2": [], "3": ["4", "6"], "4": [], "5": ["7"], "6": [], "7": []};
//       0
//     / | \
//    1--2  3
//          | \
//          4  6
//    5--7

console.log(connected_components(graph));

function connected_components(graph) {
  const components = [];
  for (const n in graph) {
    if (!visited(n)) components.push(traverse(n));
  }
  return components;

  function traverse(n) { // recursive, depth-first
    const nodes = [n];
    for (const m of graph[n]) {
      if (!visited(m)) concat_(nodes, traverse(m));
    };
    return nodes;
  }

  function concat_(a, b) {
    Array.prototype.push.apply(a, b);
  }

  function visited(n) {
    return components.flat().includes(n);
  }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2