JSFiddle - React, Tailwind, and code Playground
by Jeff Santos
HTML
<input type="button" value="Create Graph" onClick="cGraph();" />
<br/><br/> Select two nodes:
<br/><br/> From
<select id="f"></select> To
<select id="t"></select>
<input type="button" value="Calculate" onClick="calc();" />
<br/><br/>
<div id="output" />
JavaScript
function Node(value) {
this.content = value;
this.edges = [];
this.addEdge = function(otherNode, cost) {
this.edges.push({
"node": otherNode,
"cost": cost
});
}
this.toString = function() {
return this.content;
}
this.printEdges = function() {
var str = "Node: " + this.content + "\n";
for (i = 0; i < this.edges.length; i++) {
str += "to " + this.edges[i].node + " : cost = " + this.edges[i].cost + "\n";
}
return str;
}
}
function Graph() {
this.nodes = {};
this.add = function(value) {
var nNode = new Node(value);
this.nodes[value] = nNode;
return nNode;
}
this.join = function(v1, v2, cost) {
var node1 = this.nodes[v1];
var node2 = this.nodes[v2];
node1.addEdge(node2, cost);
node2.addEdge(node1, cost);
}
this.pNodes = function() {
var str = "";
for (var key in this.nodes) {
str += "Node: " + this.nodes[key] + "\n";
}
return str;
}
this.pEdges = function() {
var str = "";
for (var key in this.nodes) {
str += this.nodes[key].printEdges() + "\n";
}
return str;
}
this.BFS = function(fVal, tVal) {
var paths = [];
var q = [];
var root = this.nodes[fVal];
var tc = {};
tc[root.content] = true;
q.push({
"node": root,
"parent": null,
"cost": 0,
"checked": tc
});
while (q.length > 0) {
cur = q.dequeue();
if (cur.node.content == tVal) {
paths.push(cur);
} else {
for (i = 0; i < cur.node.edges.length; i++) {
var edge = cur.node.edges[i];
var chkS = copy(cur.checked);
if (chkS[edge.node.content] != true) {
chkS[edge.node.content] = true;
q.push({
"node": edge.node,
"parent": cur,
"cost": edge.cost,
"checked": chkS
});
}
}
}
}
return paths;
}
}
function print(out, erase =...