UNPKG

js-graph-algorithms

Version:

Package implements data structures and algorithms for processing various types of graphs

79 lines (66 loc) 2.83 kB
<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>