Breadth-First Search (graph)
Algorithm · Core
Step through it: Breadth-First Search pattern
queue: 7
Step 1 of 5
Goal: find the fewest steps from the start to everything else. Breadth-first search explores in rings: everything one step away, then everything two steps away. It uses a queue, a line where the first one in is the first one out.
Step 2 of 5
Take 7 out and add its children to the back of the line. Both are one step from the start.
Step 3 of 5
Take 9 out and add its children. Take 11 out: nothing to add. 5 and 2 are two steps away.
Step 4 of 5
Nodes are visited ring by ring, so the first time you reach a node is by the shortest route. That is why breadth-first search finds shortest paths when every step costs the same.
Step 5 of 5
Your turn.
Breadth-first search (BFS) is an algorithm for traversing, searching tree, or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key') and explores the neighbor nodes first, before moving to the next level neighbors.
Code
import Queue from '../../../data-structures/queue/Queue';
/**
* @typedef {Object} Callbacks
*
* @property {function(vertices: Object): boolean} [allowTraversal] -
* Determines whether DFS should traverse from the vertex to its neighbor
* (along the edge). By default prohibits visiting the same vertex again.
*
* @property {function(vertices: Object)} [enterVertex] - Called when BFS enters the vertex.
*
* @property {function(vertices: Object)} [leaveVertex] - Called when BFS leaves the vertex.
*/
/**
* @param {Callbacks} [callbacks]
* @returns {Callbacks}
*/
function initCallbacks(callbacks = {}) {
const initiatedCallback = callbacks;
const stubCallback = () => {};
const allowTraversalCallback = (
() => {
const seen = {};
return ({ nextVertex }) => {
if (!seen[nextVertex.getKey()]) {
seen[nextVertex.getKey()] = true;
return true;
}
return false;
};
}
)();
initiatedCallback.allowTraversal = callbacks.allowTraversal || allowTraversalCallback;
initiatedCallback.enterVertex = callbacks.enterVertex || stubCallback;
initiatedCallback.leaveVertex = callbacks.leaveVertex || stubCallback;
return initiatedCallback;
}
/**
* @param {Graph} graph
* @param {GraphVertex} startVertex
* @param {Callbacks} [originalCallbacks]
*/
export default function breadthFirstSearch(graph, startVertex, originalCallbacks) {
const callbacks = initCallbacks(originalCallbacks);
const vertexQueue = new Queue();
// Do initial queue setup.
vertexQueue.enqueue(startVertex);
let previousVertex = null;
// Traverse all vertices from the queue.
while (!vertexQueue.isEmpty()) {
const currentVertex = vertexQueue.dequeue();
callbacks.enterVertex({ currentVertex, previousVertex });
// Add all neighbors to the queue for future traversals.
graph.getNeighbors(currentVertex).forEach((nextVertex) => {
if (callbacks.allowTraversal({ previousVertex, currentVertex, nextVertex })) {
vertexQueue.enqueue(nextVertex);
}
});
callbacks.leaveVertex({ currentVertex, previousVertex });
// Memorize current vertex before next loop.
previousVertex = currentVertex;
}
}References
Practice
Breadth-First Search
- Minimum Depth of Binary TreeEasy
- Average of Levels in Binary TreeEasy
- Binary Tree Level Order TraversalMedium
- Binary Tree Zigzag Level Order TraversalMedium
- Binary Tree Right Side ViewMedium
- Populating Next Right Pointers in Each NodeMedium
- Rotting OrangesMedium
- Shortest Path in Binary MatrixMedium
- Open the LockMedium
- Walls and GatesMedium
- 01 MatrixMedium
- Perfect SquaresMedium
- Word LadderMedium
- Jump Game IIIMedium
- Nearest Exit from Entrance in MazeMedium
- Snakes and LaddersMedium
- Word Ladder IIHard
- Shortest Path Visiting All NodesHard
Spotted a mistake or something unclear? Report it on GitHub.