function search(graph, start, end) {
if (start === end) return true;
const queue = [];
for (const node of graph.getNodes()) {
node.state = 'unvisited';
}
start.state = 'visiting';
queue.push(start);
let node;
while (queue.length) {
node = queue.shift();
if (node) {
for (const neighbor of graph.getAdjacentNeighbors(node)) {
if (neighbor.state === 'unvisited') {
if (neighbor === end) {
return true;
} else {
neighbor.state = 'visiting';
queue.push(neighbor);
}
}
}
node.state = 'visited';
}
}
return false;
}
function Graph(iterable) {
this.list = new Map(iterable);
}
Graph.prototype.addVertex = function(vertex) {
!this.list.get(vertex) && this.list.set(vertex, []);
}
Graph.prototype.addEdge = function(from, to) {
this.list.get(from).push(to)
this.list.get(to).push(from);
}
Graph.prototype.getNodes = function() {
return Array.from(this.list.keys());
};
Graph.prototype.getAdjacentNeighbors = function(target) {
return this.list.get(target) || [];
}