Depth-first Search

Languages

Write a function that implements the depth-first search algorithm on a directed graph (in adjacency list format), given a starting node. Return the nodes reachable from the starting node in pre-order, visiting each node's neighbors in their listed order and including each node at most once.

If the graph is empty, return an empty array. Otherwise, the starting node is guaranteed to exist in the graph.

Examples

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']

Hints

New

Loading editor

    Depth-first Search | Algorithms Interview Questions with Solutions