Skip to content

Commit 05f68a8

Browse files
committed
connected components example
1 parent 17e832b commit 05f68a8

File tree

2 files changed

+79
-1
lines changed

2 files changed

+79
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ for(var v=0; v < g.V; ++v) {
179179

180180
### Connected Components
181181

182-
The sample code below show how to obtain the number of connected components in an undirected graph:
182+
The sample code below show how to obtain the number of connected components in an undirected graph (Link: [HTML DEMO](https://rawgit.com/chen0040/js-graph-algorithms/master/examples/example-connected-components.html)):
183183

184184
```javascript
185185
var jsgraphs = require('js-graph-algorithms');
+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
<html>
2+
<head>
3+
<title>
4+
Graph
5+
</title>
6+
<script src="../third-party-libs/vis/vis.js" type="text/javascript"></script>
7+
<script src="../src/jsgraphs.js" type="text/javascript"></script>
8+
<link href="../third-party-libs/vis/vis.css" type="text/css" />
9+
</head>
10+
11+
<body>
12+
<h2>Graph</h2>
13+
<div id="mynetwork"></div>
14+
15+
<script type="text/javascript">
16+
(function(){
17+
var g = new jsgraphs.Graph(13);
18+
g.addEdge(0, 5);
19+
g.addEdge(4, 3);
20+
g.addEdge(0, 1);
21+
g.addEdge(9, 12);
22+
g.addEdge(6, 4);
23+
g.addEdge(5, 4);
24+
g.addEdge(0, 2);
25+
g.addEdge(11, 12);
26+
g.addEdge(9,10);
27+
g.addEdge(0, 6);
28+
g.addEdge(7, 8);
29+
g.addEdge(9, 11);
30+
g.addEdge(5, 3);
31+
32+
var cc = new jsgraphs.ConnectedComponents(g);
33+
console.log(cc.componentCount()); // display 3
34+
for (var v = 0; v < g.V; ++v) {
35+
console.log('id[' + v + ']: ' + cc.componentId(v));
36+
}
37+
38+
var g_nodes = [];
39+
var g_edges = [];
40+
for(var v=0; v < g.V; ++v){
41+
g.node(v).label = 'Node ' + v; // assigned 'Node {v}' as label for node v
42+
g_nodes.push({
43+
id: v,
44+
label: g.node(v).label,
45+
group: cc.componentId(v)
46+
});
47+
48+
var adj_v = g.adj(v);
49+
for(var i = 0; i < adj_v.length; ++i) {
50+
var w = adj_v[i];
51+
if(w > v) continue; // make sure only one edge between w and v since the graph is undirected
52+
g_edges.push({
53+
from: v,
54+
to: w
55+
});
56+
};
57+
}
58+
59+
console.log(g.V); // display 6, which is the number of vertices in g
60+
console.log(g.adj(0)); // display [5, 1, 2], which is the adjacent list to vertex 0
61+
62+
var nodes = new vis.DataSet(g_nodes);
63+
64+
// create an array with edges
65+
var edges = new vis.DataSet(g_edges);
66+
67+
// create a network
68+
var container = document.getElementById('mynetwork');
69+
var data = {
70+
nodes: nodes,
71+
edges: edges
72+
};
73+
var options = {};
74+
var network = new vis.Network(container, data, options);
75+
})();
76+
</script>
77+
</body>
78+
</html>

0 commit comments

Comments
 (0)