Last active
March 9, 2017 08:07
-
-
Save vitkarpov/5b67945a7e0e79fa51457a37f2510b86 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", Graphs, 4.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Обходит граф в ширину, проверяя существует ли маршрут | |
* между указанными нодами. | |
* Предполагается, что граф представлен в виде списка смежности, | |
* проще говоря, массива где индексами являются элементы, в значениями | |
* массивы с дочерними элементами. | |
* | |
* @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