Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Last active March 9, 2017 08:07
Show Gist options
  • Save vitkarpov/5b67945a7e0e79fa51457a37f2510b86 to your computer and use it in GitHub Desktop.
Save vitkarpov/5b67945a7e0e79fa51457a37f2510b86 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", Graphs, 4.1
/**
* Обходит граф в ширину, проверяя существует ли маршрут
* между указанными нодами.
* Предполагается, что граф представлен в виде списка смежности,
* проще говоря, массива где индексами являются элементы, в значениями
* массивы с дочерними элементами.
*
* @param {Array} graph
* @param {Number} start
* @param {Number} end
* @returns {Boolean}
*/
function bst(graph, start, end) {
const visited = [];
const queue = [start];
while (queue.length > 0) {
const node = queue.shift();
const children = graph[node];
if (children) {
for (let i = 0; i < children.length; i++) {
const node = children[i];
if (visited[node]) {
continue;
}
if (node === end) {
return true;
}
visited[node] = true;
queue.push(node);
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment