forked from yangshun/lago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdepthFirstSearch.js
31 lines (28 loc) · 889 Bytes
/
depthFirstSearch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { Stack } from '../';
/**
* Performs a depth-first search on a graph given a starting node.
* @param {Object} graph Node to array of neighboring nodes.
* @param {number|string} source Source node to start traversal from. It has to exist as a node in the graph.
* @return {number[]|string[]} A DFS-traversed order of nodes.
*/
function depthFirstSearch(graph, source) {
if (Object.keys(graph).length === 0) {
return [];
}
const stack = new Stack();
stack.push(source);
const visited = new Set([source]);
while (!stack.isEmpty()) {
const node = stack.pop();
visited.add(node);
const neighbors = graph[node];
for (let i = neighbors.length - 1; i >= 0; i--) {
const neighbor = neighbors[i];
if (!visited.has(neighbor)) {
stack.push(neighbor);
}
}
}
return Array.from(visited);
}
export default depthFirstSearch;