forked from chen0040/js-graph-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample-dfs.html
79 lines (66 loc) · 2.68 KB
/
example-dfs.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<html>
<head>
<title>
Depth First Search on Graph
</title>
<script src="../third-party-libs/vis/vis.js" type="text/javascript"></script>
<script src="../src/jsgraphs.js" type="text/javascript"></script>
<link href="../third-party-libs/vis/vis.css" type="text/css" />
</head>
<body>
<h2>Depth First Search on Graph</h2>
<div id="mynetwork"></div>
<script type="text/javascript">
(function(){
var g = new jsgraphs.Graph(6);
g.addEdge(0, 5);
g.addEdge(2, 4);
g.addEdge(2, 3);
g.addEdge(1, 2);
g.addEdge(0, 1);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(0, 2);
var s = 0;
var dfs = new jsgraphs.DepthFirstSearch(g, s);
var g_nodes = [];
var g_edges = [];
for(var v=0; v < g.V; ++v){
g.node(v).label = 'Node ' + v; // assigned 'Node {v}' as label for node v
g_nodes.push({
id: v,
label: g.node(v).label
});
if(v != s && dfs.hasPathTo(v)) {
console.log(s + " is connected to " + v);
var path = dfs.pathTo(v);
for(var j = 1; j < path.length; ++j) {
var x1 = path[j-1];
var x2 = path[j];
g_edges.push({
from: x1,
to: x2,
arrows: 'to'
});
}
} else {
console.log('No path from ' + s + ' to ' + v);
}
}
console.log(g.V); // display 6, which is the number of vertices in g
console.log(g.adj(0)); // display [5, 1, 2], which is the adjacent list to vertex 0
var nodes = new vis.DataSet(g_nodes);
// create an array with edges
var edges = new vis.DataSet(g_edges);
// create a network
var container = document.getElementById('mynetwork');
var data = {
nodes: nodes,
edges: edges
};
var options = {};
var network = new vis.Network(container, data, options);
})();
</script>
</body>
</html>