function Graph() {
this.vertices = [];
this.edges = 0;
this.vertexEdges = {};
this.marked = {};
this.dist = [];
this.path = [];
}
Graph.prototype = {
addVertex: function(v) {
this.vertices.push(v);
this.vertexEdges[v] = [];
this.marked[v] = false;
this.dist[v] = -1;
this.path[v] = -1;
},
addEdge: function(v, w) {
this.vertexEdges[v].push(w);
this.vertexEdges[w].push(v);
this.edges++;
},
show: function() {
for (var i = 0, len = this.vertices.length; i < len; i++) {
var v = this.vertices[i];
var ves = this.vertexEdges[v];
var str = v + ' -> ';
for (var j = 0, subl = ves.length; j < subl; j++) {
str += ' ' + ves[j] + ' ';
}
console.log(str + '\n');
}
},
bfsTraverse: function(v) {
this.marked[v] = true;
var queue = [];
queue.push( v );
while (queue.length > 0) {
var v = queue.shift();
var ves = this.vertexEdges[v];
console.log(v);
for (var i = 0, len = ves.length; i < len; i++) {
if ( !this.marked[ ves[i] ] ) {
this.marked[ ves[i] ] = true;
queue.push(ves[i]);
}
}
}
},
dfsTraverse: function(v) {
this.marked[v] = true;
var ves = this.vertexEdges[v];
console.log(v);
for (var i = 0, len = ves.length; i < len; i++) {
if ( !this.marked[ ves[i] ] ) {
this.marked[ ves[i] ] = true;
this.dfsTraverse(ves[i])
}
}
},
bfsFindPath: function(v) {
this.dist[v] = 0;
var queue = [];
queue.push( v );
while (queue.length > 0) {
var v = queue.shift();
var ves = this.vertexEdges[v];
for (var i = 0, len = ves.length; i < len; i++) {
if ( this.dist[ ves[i] ] == -1 ) {
this.dist[ ves[i] ] = this.dist[ v ] + 1;
this.path[ ves[i] ] = v;
queue.push(ves[i]);
}
}
}
console.log(this.dist, this.path)
},
}
var graph = new Graph();
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'].forEach(function(v) {
graph.addVertex(v)
});
graph.addEdge('A', 'B')
graph.addEdge('A', 'C')
graph.addEdge('A', 'D')
graph.addEdge('C', 'D')
graph.addEdge('C', 'G')
graph.addEdge('D', 'G')
graph.addEdge('D', 'H')
graph.addEdge('B', 'E')
graph.addEdge('B', 'F')
graph.addEdge('E', 'I')
graph.bfsFindPath('H')