[Algorithm] Breadth First JavaScript Search Algorithm for Graphs
Breadth first search is a graph search algorithm that starts at one node and visits neighboring nodes as widely as possible before going further down any other path. This algorithm requires the use of a queue to keep track of which nodes to visit, so it might be worth your time to brush up on that data structure before watching this lesson.
const {createQueue} = require('./queue'); function createNode(key) {
let children = [];
return {
key,
children,
addChild(child) {
children.push(child)
}
}
} function createGraph(directed = false) {
const nodes = [];
const edges = []; return {
nodes,
edges,
directed, addNode(key) {
nodes.push(createNode(key))
}, getNode (key) {
return nodes.find(n => n.key === key)
}, addEdge (node1Key, node2Key) {
const node1 = this.getNode(node1Key);
const node2 = this.getNode(node2Key); node1.addChild(node2); if (!directed) {
node2.addChild(node1);
} edges.push(`${node1Key}${node2Key}`)
}, print() {
return nodes.map(({children, key}) => {
let result = `${key}`; if (children.length) {
result += ` => ${children.map(n => n.key).join(' ')}`
} return result;
}).join('\n')
},
/**
* Breadth First Search
*/
bfs (startNodeKey = "", visitFn = () => {}) {
/**
* Keytake away:
* 1. Using Queue to get next visit node
* 2. Enqueue the node's children for next run
* 3. Hashed visited map for keep tracking visited node
*/
const startNode = this.getNode(startNodeKey);
// create a hashed map to check whether one node has been visited
const visited = this.nodes.reduce((acc, curr) => {
acc[curr.key] = false;
return acc;
}, {}); // Create a queue to put all the nodes to be visited
const queue = createQueue();
queue.enqueue(startNode); // start process
while (!queue.isEmpty()) {
const current = queue.dequeue(); // check wheather the node exists in hashed map
if (!visited[current.key]) {
visitFn(current);
visited[current.key] = true; // process the node's children
current.children.map(n => {
if (!visited[n.key]) {
queue.enqueue(n);
}
});
}
}
}
}
} const graph = createGraph(true) graph.addNode('Kyle')
graph.addNode('Anna')
graph.addNode('Krios')
graph.addNode('Tali') graph.addEdge('Kyle', 'Anna')
graph.addEdge('Anna', 'Kyle')
graph.addEdge('Kyle', 'Krios')
graph.addEdge('Kyle', 'Tali')
graph.addEdge('Anna', 'Krios')
graph.addEdge('Anna', 'Tali')
graph.addEdge('Krios', 'Anna')
graph.addEdge('Tali', 'Kyle') console.log(graph.print()) const nodes = ['a', 'b', 'c', 'd', 'e', 'f']
const edges = [
['a', 'b'],
['a', 'e'],
['a', 'f'],
['b', 'd'],
['b', 'e'],
['c', 'b'],
['d', 'c'],
['d', 'e']
] const graph2 = createGraph(true)
nodes.forEach(node => {
graph2.addNode(node)
}) edges.forEach(nodes => {
graph2.addEdge(...nodes)
}) graph2.bfs('a', node => {
console.log(node.key) //a,b,e,f,d,c
})
A more general function:
bfs (startNodeKey, predFn = () => {}, cb = () => {}) {
const startNode = this.getNode(startNodeKey);
const visited = createVistedMap(this.nodes);
const queue = createQueue();
startNode.children.forEach((n) => {
queue.enqueue(n);
});
while (!queue.isEmpty()) {
const current = queue.dequeue();
if (!visited[current.key]) {
if (predFn(current)) return cb(current);
else {
visited[current.key] = true;
}
}
}
cb(null)
},
let graph3 = createGraph(true)
const tyler = {key: 'tyler', dog: false};
const henry = {key: 'henry', dog: false};
const john = {key: 'john', dog: false};
const aimee = {key: 'aimee', dog: true};
const peggy = {key: 'peggy', dog: false};
const keli = {key: 'keli', dog: false};
const claire = {key: 'claire', dog: false}; graph3.addNode('tyler', tyler);
graph3.addNode('henry', henry);
graph3.addNode('john', john);
graph3.addNode('claire', claire);
graph3.addNode('aimee', aimee);
graph3.addNode('peggy', peggy)
graph3.addNode('keli', keli); graph3.addEdge('tyler', 'henry')
graph3.addEdge('tyler', 'john')
graph3.addEdge('tyler', 'aimee')
graph3.addEdge('henry', 'keli')
graph3.addEdge('henry', 'peggy')
graph3.addEdge('john', 'john')
graph3.addEdge('keli', 'claire') graph3.bfs2('tyler', (node) => {
return node.dog;
}, (node) => {
if (node) console.log(`${node.key} has a dog`)
else console.log('Tyler friends has no dog')
})
Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.
[Algorithm] Breadth First JavaScript Search Algorithm for Graphs的更多相关文章
- [Algorithm] Beating the Binary Search algorithm – Interpolation Search, Galloping Search
From: http://blog.jobbole.com/73517/ 二分检索是查找有序数组最简单然而最有效的算法之一.现在的问题是,更复杂的算法能不能做的更好?我们先看一下其他方法. 有些情况下 ...
- [Algorithm] Write a Depth First Search Algorithm for Graphs in JavaScript
Depth first search is a graph search algorithm that starts at one node and uses recursion to travel ...
- [Algorithms] Binary Search Algorithm using TypeScript
(binary search trees) which form the basis of modern databases and immutable data structures. Binary ...
- [Algorithm] A* Search Algorithm Basic
A* is a best-first search, meaning that it solves problems by searching amoung all possible paths to ...
- TSearch & TFileSearch Version 2.2 -Boyer-Moore-Horspool search algorithm
unit Searches; (*-----------------------------------------------------------------------------* | Co ...
- 笔试算法题(48):简介 - A*搜索算法(A Star Search Algorithm)
A*搜索算法(A Star Search Algorithm) A*算法主要用于在二维平面上寻找两个点之间的最短路径.在从起始点到目标点的过程中有很多个状态空间,DFS和BFS没有任何启发策略所以穷举 ...
- 【437】Binary search algorithm,二分搜索算法
Complexity: O(log(n)) Ref: Binary search algorithm or 二分搜索算法 Ref: C 版本 while 循环 C Language scripts b ...
- js binary search algorithm
js binary search algorithm js 二分查找算法 二分查找, 前置条件 存储在数组中 有序排列 理想条件: 数组是递增排列,数组中的元素互不相同; 重排 & 去重 顺序 ...
- PatentTips - Adaptive algorithm for selecting a virtualization algorithm in virtual machine environments
BACKGROUND A Virtual Machine (VM) is an efficient, isolated duplicate of a real computer system. Mor ...
随机推荐
- selenium 自动化测试 Chrome 大于 63 版本 不能重定向问题解决办法
Chrome 一些信息: Chrome 63 以后,浏览器默认屏蔽了重定向 Chrome 63 版本,设置了禁止更新,有些情况还是会更新到最新版本 解决过程: 在博客上查到 selenium 里 给 ...
- 和为n连续正数序列 【微软面试100题 第五十一题】
题目要求: 输入一个正数n,输出所有和为n连续正数序列(至少两个). 例如输入15,由于1+2+3+4+5 = 4+5+6 = 7+8 = 15.所以输出3个连续序列1~5,4~6,7~8. 参考资料 ...
- day03_07 变量的重新赋值01
在cmd中退出python,需要使用quit()命令 name = "Alex Li" name2 = name print(name,name2) name = "Ja ...
- matlab 初级画图
matlab 初级画图 1.plot() plot(x,y) plots each vector pairs (x,y) 画图函数画出每个点 每组变量 plot (y) plots eac ...
- TensorFlow——小练习:counter
下面的例子演示了如何使用变量实现一个 简单的计数器(counter) # _*_coding:utf-8_*_ import tensorflow as tf import numpy as np # ...
- linux 系统时间调整
linux的硬件时间是从COMS中读取的. 系统时间是由操作系统维护的. 先查看时区是否正确 (东八区 +8) #date -R 选择时区: #tzselect 修改了系统时间,还应该跟硬件时间进行同 ...
- java面试题之Error和Exception的区别
从概念角度分析: Error:程序无法处理的系统错误,编译器不做检查: Exception:程序可以处理的异常,捕获后可能恢复: 总结:前者是程序无法处理的错误,后者是可以处理的异常. 从责任角度分析 ...
- hust 1605 - Gene recombination(bfs+字典树)
1605 - Gene recombination Time Limit: 2s Memory Limit: 64MB Submissions: 264 Solved: 46 DESCRIPTION ...
- js simple drag.
// by zhangxinxu welcome to visit my personal website http://www.zhangxinxu.com/ // zxx.drag v1.0 20 ...
- 应用seajs 做了个向上滚动的demo
目录结构式这样滴 sea sea-module jquery-1.10.2.min.js sea.js static css t.min.css img test test.min.js main.j ...