Algorithm for searching graph-like data structures, one level at a time.
- Start a queue
- Check current node - if false, mark as visited, continue
- Add all unvisited, connected nodes to queue
- Check one by one like the previous node and repeat
function bfs(value, node) {
let ticks = 0;
queue = [];
queue.unshift(node);
while (queue.length > 0) {
ticks++
curNode = queue.pop();
if (curNode.value === value) {
return {node: curNode, ticks};
}
let len = curNode.children.length;
for (let i = 0; i < len; i++) {
queue.unshift(curNode.children[i]);
}
}
return {node: null, ticks}
}
O(n^2)
- Solution is not far from the root of the tree
- Tree is very deep and solutions are rare
Algorithm for searching graph-like data structures... aggresively.
- Check current node - if found, return node
- For that node find the length of children
- For that length, recursively repeat search
function dfs(value, node) {
if (node.value === value) {
return node;
}
var len = node.children.length;
for (var i = 0; i < len; i++) {
var foundNode = dfs(value, node.children[i]);
if (foundNode) {
return foundNode;
}
}
return null;
}
function dfs(value, node) {
let ticks = 0;
stack = [];
stack.push(node);
while (stack.length !== 0) {
ticks++;
let curNode = stack.pop();
if (curNode.value == value) {
return {node: curNode, ticks};
}
let len = curNode.children.length;
for (let i = 0; i < len; i++) {
stack.push(curNode.children[i]);
}
}
return {node: null, ticks}
}
O(n^2)
- Much lower memory requirements (compared to BFS)
- Common, usually far from root
no, it was for teaching purposes only