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

  1. [Algorithm] A* Search Algorithm Basic

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

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

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

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

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

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

  5. [Algorithms] Binary Search Algorithm using TypeScript

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

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

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

  7. js binary search algorithm

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

  8. [算法&数据结构]深度优先搜索(Depth First Search)

    深度优先 搜索(DFS, Depth First Search) 从一个顶点v出发,首先将v标记为已遍历的顶点,然后选择一个邻接于v的尚未遍历的顶点u,如果u不存在,本次搜素终止.如果u存在,那么从u ...

  9. JAVA使用HttpClient时报错:Algorithm constraints check failed on signature algorithm: MD5withRSA

    今天使用httpClient.executeMethod时抛出异常:java.security.cert.CertPathValidatorException: Algorithm constrain ...

随机推荐

  1. dev c++ 提示没有iostream.h文件

    dev c++ 提示没有iostream.h文件 解决办法路径没有打通最好是这样写:#include <iostream>using namespace std;int main(int ...

  2. Python面向对象(组合、菱形继承、多态)

    今日内容: 1.组合 2.菱形继承 3.多态与多态性 昨天内容重点回顾: 1)调用也叫实例化:发生了2件事  1.创造空对象  2.触发对象下的__init__方法,然后将p连同参数一同传给init  ...

  3. 解决MySQL版本之间造成的乱码、数据查询不出的问题

    在数据库连接字符串上加  charset=utf8 <connectionStrings> <add name="XJRDSModels" connectionS ...

  4. Linux下安装Mysql出现的常见问题以及解决办法

     1.安装时候出现 warning: mysql-community-server-5.7.13-1.el6.x86_64.rpm: Header V3 DSA/SHA1 Signature, key ...

  5. webpack的像素转vw单位的loader插件

    安装: npm i px2vw-view-loader 配置: 按以下loader格式,添加进入webpack配置文件,实现从px转换成vw,适用于移动端项目 module: { rules: [{ ...

  6. Python Mysql学习总结

    任何应用都离不开数据,所以在学习python的时候,当然也要学习一个如何用python操作数据库了.MySQLdb就是python对mysql数据库操作的模块.官方Introduction : MyS ...

  7. pytorch conditional GAN 调试笔记

    推荐的几个开源实现 znxlwm 使用InfoGAN的结构,卷积反卷积 eriklindernoren 把mnist转成1维,label用了embedding wiseodd 直接从tensorflo ...

  8. [HDNOIP2017提高组]题解

    (送给外省的同学们:HD = 海淀) [HDNOIP201701]小鱼干 试题描述 小喵喵有 n 个小鱼干排成一列,其中第 i 个小鱼干有两种属性,美味度 ai 和特殊度 bi. 现在小喵喵要吃掉一些 ...

  9. 【前端学习笔记】2015-09-06 ~~~~ setAttribute()、slice()

    所遇记录: 1.setAttribute("属性",value),相同的还有addAttribute("属性名",value),getAttribute(“属性 ...

  10. [LeetCode] Sort Colors 只有3个类型的排序

    Given an array with n objects colored red, white or blue, sort them so that objects of the same colo ...