[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 ...
随机推荐
- 使用代码生成器“代码工厂”快速生成B/S程序代码
开发目的: 自动生成C#.HTML.JS.Ajax 代码 .可以节省大量的时间来做业务逻辑的代码,那些重复的代码就不需要....了 环境支持: 硬件环境:window .VS2010+.支持SQLSe ...
- ip 核生成 rom 及questasim仿真时需要注意的问题
IP 核生成 ROM 步骤1:Tools --> MegaWizard Plug-In Manager 步骤2:Create a new custom megafuction variation ...
- [python][oldboy]python涉及的几种编码
1 python文件代码中中文的识别 (换言之,python代码的中文不显示乱码)和解析u"中文"这样的unicode对象 # coding=utf8 2 python运行环境(I ...
- [java开发篇][dom4j模块] 遍历xml文件
http://blog.csdn.net/chenleixing/article/details/44353491 在android studio 导入dom4j库(build-gradle(Moud ...
- CodeForces839D[莫比乌斯反演] Codeforces Round #428 (Div. 2)
/*CodeForces839D[莫比乌斯反演]*/ #include <bits/stdc++.h> typedef long long LL; const LL MOD = 10000 ...
- 【Vjudge】P1989Subpalindromes(线段树)
题目链接 水题一道,用线段树维护哈希值,脑补一下加减乱搞搞……注意细节就过了 一定注意细节…… #include<cstdio> #include<cstdlib> #incl ...
- HDU——1874畅通工程续(邻接矩阵弗洛伊德)
畅通工程续 Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submi ...
- 线程与threading模块
线程 进程内一个相对独立的.可调度的执行单元,是系统独立调度和分派CPU的基本单位.在单个进程中同时运行多个线程完成不同的工作,称为多线程. 同一进程内的多个线程是共享该进程的资源. 创建新的线程开销 ...
- FZOJ Problem 2150 Fire Game
...
- 【BZOJ1018】堵塞的交通traffic(线段树,网格图,连通性)
题意:一个2行C列的矩形网格图,网格上的每个点代表一个城市,相邻的城市之间有一条道路 一开始每条道路都是堵塞的,堵塞即为不可经过.经过一些操作后,可能某些道路通畅了,也可能某些道路堵塞了 多次询问,询 ...