Breadth-first Search

语言

Write a function breadthFirstSearch(graph, source) that implements the breadth-first search (BFS) algorithm on a directed graph (in adjacency list format), given a starting node (source).

BFS is an algorithm used for traversing a graph or a tree, starting from the root node and exploring all the neighbors at the current depth before moving on to nodes at the next depth level. The output from BFS is an array of the graph's nodes in the order they were traversed. Visiting neighboring nodes in any order is a valid BFS, but for this question, please visit each node's neighbors from left to right.

Examples

const graph1 = {
A: ['B', 'C', 'D'],
B: ['E', 'F'],
C: ['G', 'H'],
D: ['I', 'J'],
E: ['D'],
F: [],
G: [],
H: [],
I: [],
J: [],
};
breadthFirstSearch(graph1, 'A'); // ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
Illustration of graph1 from node 'A'
breadthFirstSearch(graph1, 'B'); // ['B', 'E', 'F', 'D', 'I', 'J']
Illustration of graph1 from node 'B'
const graph2 = {
A: ['B', 'C'],
B: ['D', 'E'],
C: ['F', 'G'],
D: [],
E: [],
F: [],
G: [],
};
breadthFirstSearch(graph2, 'A'); // ['A', 'B', 'C', 'D', 'E', 'F', 'G']
Illustration of graph2 from node 'A'
breadthFirstSearch(graph2, 'E'); // ['E']
breadthFirstSearch({}, ''); // []

Note:

  • Return an empty array if the graph is empty.
  • The source node, if provided, is guaranteed to be present in graph.

A Queue data structure is also provided for you at the bottom of the skeleton code.

Hints

加载编辑器

    Breadth-first Search | 算法面试题及解决方案