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的更多相关文章

  1. [Algorithm] Beating the Binary Search algorithm – Interpolation Search, Galloping Search

    From: http://blog.jobbole.com/73517/ 二分检索是查找有序数组最简单然而最有效的算法之一.现在的问题是,更复杂的算法能不能做的更好?我们先看一下其他方法. 有些情况下 ...

  2. [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 ...

  3. [Algorithms] Binary Search Algorithm using TypeScript

    (binary search trees) which form the basis of modern databases and immutable data structures. Binary ...

  4. [Algorithm] A* Search Algorithm Basic

    A* is a best-first search, meaning that it solves problems by searching amoung all possible paths to ...

  5. TSearch & TFileSearch Version 2.2 -Boyer-Moore-Horspool search algorithm

    unit Searches; (*-----------------------------------------------------------------------------* | Co ...

  6. 笔试算法题(48):简介 - A*搜索算法(A Star Search Algorithm)

    A*搜索算法(A Star Search Algorithm) A*算法主要用于在二维平面上寻找两个点之间的最短路径.在从起始点到目标点的过程中有很多个状态空间,DFS和BFS没有任何启发策略所以穷举 ...

  7. 【437】Binary search algorithm,二分搜索算法

    Complexity: O(log(n)) Ref: Binary search algorithm or 二分搜索算法 Ref: C 版本 while 循环 C Language scripts b ...

  8. js binary search algorithm

    js binary search algorithm js 二分查找算法 二分查找, 前置条件 存储在数组中 有序排列 理想条件: 数组是递增排列,数组中的元素互不相同; 重排 & 去重 顺序 ...

  9. 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 ...

随机推荐

  1. luogu2473 [SCOI2008]奖励关

    题解参照这里 每个研究完记得乘一个1/n,这是乘了概率. #include <iostream> #include <cstdio> using namespace std; ...

  2. luogu2455 [SDOI2006]线性方程组 高斯消元法

    #include <iostream> #include <cstdio> #include <cmath> using namespace std; int n, ...

  3. Objective-C中的一些特殊的数据类型

    nil nil和C语言的NULL相同,在objc/objc.h中定义.nil表示一个Objctive-C对象,这个对象的指针指向空(没有东西就是空). Nil  首字母大写的Nil和nil有一点不一样 ...

  4. Spider爬虫-get、post请求

    1:概念: 爬虫就是通过编写程序,模拟浏览器上网,然后让其去互联网上抓取数据的过程. 2:python爬虫与其他语言的比较: (1)php爬虫弊端:多进程多线程支持的不好 (2)java:代码臃肿,重 ...

  5. 九度oj 题目1083:特殊乘法 清华大学2010年机试题目

    题目描述: 写个算法,对2个小于1000000000的输入,求结果. 特殊乘法举例:123 * 45 = 1*4 +1*5 +2*4 +2*5 +3*4+3*5 输入: 两个小于1000000000的 ...

  6. mysql 游标的使用总结

    一.游标的基本概念 游标:游标是一个存储在Mysql服务器上的数据库查询,它不是一条select语句,而是被该语句检索出来的结果集. 本人,学习游标中,曾遇到一个问题,循环总是最后多执行一次.下面分析 ...

  7. LibreOJ2043 - 「CQOI2016」K 远点对

    Portal Description 给出平面上的\(n(n\leq10^5)\)个整点,求在欧几里得距离下第\(k\)远的点对之间的距离. Solution k-d树+堆. 用小根堆维护当前找到的第 ...

  8. 瞄一眼LongAdder(jdk11)

    java版本11.0.1,感觉写得太水了,等心情好的时候再重新编辑一下. LongAdder中的核心逻辑主要由java.util.concurrent.atomic.Striped64维护,作为Str ...

  9. mysql 查询死锁语句

    我们可以用下面三张表来查原因:        innodb_trx ## 当前运行的所有事务        innodb_locks ## 当前出现的锁        innodb_lock_wait ...

  10. P1340 送礼物

    时间: 1000ms / 空间: 131072KiB / Java类名: Main 描述 作为惩罚,GY被遣送去帮助某神牛给女生送礼物(GY:貌似是个好差事)但是在GY看到礼物之后,他就不这么认为了. ...