Write a function that implements the depth-first search algorithm on a directed graph (in adjacency list format), given a starting node.
const graph1 = {A: ['B', 'C', 'D'],B: ['E', 'F'],C: ['G', 'H'],D: ['I', 'J'],E: ['D'],F: [],G: [],H: [],I: [],J: [],};depthFirstSearch(graph1, 'A'); // ['A', 'B', 'E', 'D', 'I', 'J', 'F', 'C', 'G', 'H']depthFirstSearch(graph1, 'B'); // ['B', 'E', 'D', 'I', 'J', 'F']const graph2 = {A: ['B', 'C'],B: ['D', 'E'],C: ['F', 'G'],D: [],E: [],F: [],G: [],};depthFirstSearch(graph2, 'A'); // ['A', 'B', 'D', 'E', 'C', 'F', 'G']depthFirstSearch(graph2, 'E'); // ['E']
Depth-first search (DFS) is an algorithm used for traversing a graph or a tree. The output from DFS is an array of the graph's nodes in the order they were traversed. This output is useful for a variety of different use cases and purposes, which makes DFS a useful algorithm to know. Some use cases:
Here is an overview of how DFS works to traverse a graph, using the standard implementation that takes in an adjacency list (we use an array instead) and the root node: