Simple Implementation of a Graph
by Nyle Anderson
HTML
<input type="button" onclick="createGraph();" value="Create Graph" />
<br/>
<br/> Select two nodes:
<br />From
<select id="from"></select>
To
<select id="to"></select>
<input type="button" onclick="calculate();" value="Calculate" />
<br/>
<p id="nodes"></p>
<br/>
<p id="edges"></p>
<br/>
<p id="paths"></p>
<br/><span id="result" />
JavaScript
var Node = function(_name) {
this.name = _name;
this.edges = [];
return this;
}
var Edge = function(_cost) {
this.from = null;
this.to = null;
this.cost = null;
return this;
}
var Graph = function() {
this.nodes = [];
this.edges = [];
this.paths = [];
this.addNode = function(_name) {
var node = new Node(_name);
this.nodes.push(node);
return node;
};
this.addEdge = function(_from, _to, _cost) {
var edge = new Edge(_cost);
edge.from = _from;
edge.to = _to;
edge.cost = _cost;
this.edges.push(edge);
return edge;
};
this.printNodes = function() {
var s = "All Nodes in Graph <br/>";
for (var i = 0; i < this.nodes.length; i++) {
s = s + "Node: " + i + " Name: " + this.nodes[i].name + "</br>";
}
return s;
}
this.printEdges = function() {
var s = "All Edges in Graph <br/>";
for (var i = 0; i < this.edges.length; i++) {
s += "Edge: " + i + " From: " + this.edges[i].from.name + " To: " + this.edges[i].to.name + " Cost: " + this.edges[i].cost + "</br>";
}
return s;
}
//depth first search
this.calculatePaths = function() {
this.marked = [];
for (var i = 0; i < this.vertices; ++i) {
this.marked[i] = false;
}
function dfs(_to) {
this.marked[_to] = true;
if (this.adj[_to] != undefined)
document.getElementById("paths").innerHTML=("Visited vertex: " + _to);
for each (var _from in this.adj[_to]) {
if (!this.marked[_from]) {
this.dfs(_from);
}
}
}
return this.paths;
}
this.printPaths = function() {
if (this.adj[_to] != undefined)
document.getElementById("paths").innerHTML=("Visited vertex: " + _to);
for each (var _from in this.adj[_to]) {
if (!this.marked[_from]) {
this.dfs(_from);
}
}
return this.paths;
}
}
var nodeList = document.getElementById("nodes");
var graph = new Graph(); // Global
function...