class Graph {
constructor() {
this.v = {};
this.vLen = 0;
this.eLen = 0;
}
addEdge(from, to) {
if (!this.v[from.id]) {
this.v[from.id] = {};
this.v[from.id]['node'] = from;
this.v[from.id]['edge'] = [];
this.vLen++;
}
if (!this.v[to.id]) {
this.v[to.id] = {};
this.v[to.id]['node'] = to;
this.v[to.id]['edge'] = [];
this.vLen++;
}
this.v[from.id]['edge'].push(to);
this.v[to.id]['edge'].push(from);
this.eLen++;
}
}
class Operation {
constructor(graph) {
this.graph = graph;
this.marked = {};
}
count(node) {
if (node !== void 0) {
if (this.graph['v'][node.id]) {
return this.graph['v'][node.id]['edge'].length;
} else {
return 0;
}
} else {
for (var key in this.graph['v']) {
console.log(this.graph['v'][key]['edge'].length)
}
}
},
traversalDFS(node) {
if (this.marked[node.id]) {
return;
}
console.log(node.id);
this.marked[node.id] = true;
var v = this.graph['v'][node.id]['edge'];
for (var i = 0; i < v.length; i++) {
if (!this.marked[v[i].id]) {
this.traversal(v[i])
}
}
},
traversalBFS(node) {
var i = 0;
var queue = [node];
var point;
var v;
var marked = {};
while(point = queue.shift()) {
if (marked[point.id]) {
continue;
} else {
console.log(point.id);
marked[point.id] = true;
}
v = this.graph['v'][point.id]['edge'];
queue = queue.concat(v);
}
}
}
var graph = new Graph();
for(var i = 0; i < 5; i++) {
var from = {id: i};
var to = {id: i + 1};
graph.addEdge(from, to);
}
graph.addEdge({id: 2}, {id: 5});
graph.addEdge({id: 1}, {id: 4});
var op = new Operation(graph)
op.traversalDFS(graph, {id:4})
op.traversalBFS(graph, {id:1})