[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 as deeply down a path of neighboring nodes as possible, before coming back up and trying other paths.
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);
}
});
}
}
}, /**
* Depth First Search
*/
dfs (startNodeKey = "", visitFn = () => {}) {
// get starting node
const startNode = this.getNode(startNodeKey);
// create hashed map
const visited = this.nodes.reduce((acc, curr) => {
acc[curr] = false;
return acc;
}, {});
function explore(node) {
// if already visited node, return
if (visited[node.key]) {
return;
}
// otherwise call the callback function
visitFn(node);
// Set nodekey to be visited
visited[node.key] = true;
// Continue to explore its children
node.children.forEach(n => {
explore(n);
});
}
// start exploring
explore(startNode);
}
}
} 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)
}) console.log('***Breadth first graph***')
graph2.bfs('a', node => {
console.log(node.key)
}) console.log('***Depth first graph***')
graph2.dfs('a', node => {
console.log(node.key)
})
So Depth first Search VS Breadth first Search:
Using 'depth' in JS, we should remind ourselves recursion, which using Stack data structure, FILO;
Using 'breadth', we should remind ourselves Queue, it is FIFO data structure, we just need to enqueue the all the children.
[Algorithm] Write a Depth First Search Algorithm for Graphs in JavaScript的更多相关文章
- [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 ...
- [Algorithm] Breadth First JavaScript Search Algorithm for Graphs
Breadth first search is a graph search algorithm that starts at one node and visits neighboring node ...
- 笔试算法题(48):简介 - A*搜索算法(A Star Search Algorithm)
A*搜索算法(A Star Search Algorithm) A*算法主要用于在二维平面上寻找两个点之间的最短路径.在从起始点到目标点的过程中有很多个状态空间,DFS和BFS没有任何启发策略所以穷举 ...
- [Algorithms] Binary Search Algorithm using TypeScript
(binary search trees) which form the basis of modern databases and immutable data structures. Binary ...
- 【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 二分查找算法 二分查找, 前置条件 存储在数组中 有序排列 理想条件: 数组是递增排列,数组中的元素互不相同; 重排 & 去重 顺序 ...
- [算法&数据结构]深度优先搜索(Depth First Search)
深度优先 搜索(DFS, Depth First Search) 从一个顶点v出发,首先将v标记为已遍历的顶点,然后选择一个邻接于v的尚未遍历的顶点u,如果u不存在,本次搜素终止.如果u存在,那么从u ...
- JAVA使用HttpClient时报错:Algorithm constraints check failed on signature algorithm: MD5withRSA
今天使用httpClient.executeMethod时抛出异常:java.security.cert.CertPathValidatorException: Algorithm constrain ...
随机推荐
- 【Codeforces Round #476 (Div. 2) [Thanks, Telegram!] C】Greedy Arkady
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 枚举那个人收到了几次糖i. 最好的情况显然是其他人都只收到i-1次糖. 然后这个人刚好多收了一次糖 也即 (i-1)kx + x & ...
- Apache不能启动: Unable to open logs
日志名称: Application来源: Apache Service日期: 2014/3/12 14:43:21事件 ID: ...
- MongoDB 3.6 安装详解
在ubuntu和多数linux发行版的包安装源中MongoDB默认的版本是2.4,但2.4所使用的存储引擎不支持collecitons级别的锁,只支持database级别的,所以在开发中2.4版本的m ...
- 九度oj 1003
前几天开刷九度oj,准备把做的题都放上,先放1003 题目1003:A+B 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:16923 解决:7029 题目描述: 给 ...
- mybatis的嵌套查询(嵌套查询nested select和嵌套结果nested results查询)区别
(转自:http://blog.csdn.net/canot/article/details/51485955) Mybatis表现关联关系比hibernate简单,没有分那么细致one-to-man ...
- iOS--------对堆、栈 存储空间的理解
Objective-C的对象在内存中是以堆的方式分配空间的,并且堆内存是由你释放的,即release 栈由编译器管理自动释放的,在方法中(函数体)定义的变量通常是在栈内,因此如果你的变量要跨函数的话就 ...
- iOS学习笔记43-Swift(三)类
一.Swift的类class 作为一门面向对象语言,类也是Swift的非常重要的类型,我们先来看下一个简单的类 //Swift中一个类可以不继承于任何其他基类,那么此类本身就是一个基类 class P ...
- 【bzoj3251】树上三角形 朴素LCA+暴力
题目描述 给定一大小为n的有点权树,每次询问一对点(u,v),问是否能在u到v的简单路径上取三个点权,以这三个权值为边长构成一个三角形.同时还支持单点修改. 输入 第一行两个整数n.q表示树的点数和操 ...
- Python Base Three
//sixth day to study python(2016/8/7) 32. In python , there are have an special type dictionary , it ...
- [转] 细说linux挂载——mount
转载的文章不能分类 这点比较坑 暂时先发到随笔里了 标题会标注的 找到一篇写的对挂载比较好的文章 收藏ing 作者:adagio Ubuntu社区 原帖网址:http://forum.ubu ...