Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Breadth-First Search

Graphs Overview


max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
Like Depth-First Search, breadth-first search is also used to traverse graphs. In this section, we'll cover how to implement BFS on both adjacency lists and matrices, as well as the types of problems that are best solved using BFS.
Just like with depth-first search, the most important thing to remember when implementing BFS on a graph is to keep track of visited nodes to avoid infinite loops. If we try to enqueue a node that has already been visited, we should skip it instead of adding it to the queue.

BFS on an Adjacency List

To traverse a graph represented with an adjacency list with BFS:
  • Choose a starting node and add it to the queue (we start with the first node in the adjacency list Node "1" in the example below).
  • While the queue is not empty, remove the node at the front of the queue and add it to the set of visited nodes.
  • Add the children of the node to the back of the queue (if they haven't been visited yet).
  • Repeat steps 2 and 3 until the queue is empty.
The animation shows how BFS traverses the graph represented by:
Solution
Python
Language
adjList = {
"1": ["2", "4"],
"2": ["1", "3"],
"3": ["2", "4"],
"4": ["1", "3", "5"],
"5": ["4"]
}
Visualization
Python
Language
from collections import deque
def bfs(start):
visited = set([start])
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in adjList[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
54321

0 / 11

BFS on an Matrix (2D Grid)

To traverse a graph represented as a matrix with BFS:
  • Choose a starting node and add it to the queue (we start with top left node in the example below).
  • While the queue is not empty, remove the node at the front of the queue and add it to the set of visited nodes.
  • Add the four neighbors of the node to the back of the queue (if they haven't been visited yet and are within the bounds of the matrix).
  • Repeat steps 2 and 3 until the queue is empty.
The animation shows how BFS traverses the graph represented by:
Solution
Python
Language
matrix = [
[0, 0, 0],
[0, 1, 1],
[0, 1, 0]
]
Visualization
Python
Language
from collections import deque
def bfs(grid):
visited = set()
# up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
queue = deque([(0, 0)])
visited.add((0, 0))
while queue:
row, col = queue.popleft()
# enqueue neighbors
for dr, dc in directions:
n_row = row + dr
m_col = col + dc
# check bounds and if neighbor is visited
if 0 <= n_row < len(grid) \
and 0 <= m_col < len(grid[0]) \
and (n_row, m_col) not in visited:
queue.append((n_row, m_col))
visited.add((n_row, m_col))
000011010

0 / 20

Nodes at a Level

Like binary trees, graphs can also have levels. In a graph, a level is defined as the number of edges between the root node and the current node, which is also known as the "distance" between the two nodes.
This is the primary use case of BFS in graphs: to solve questions that involve traversing the graph level-by-level, so we should be familiar with this pattern for both adjacency lists and matrices.
0123123423453456
Nodes in a 2D-grid labeled with their distance from the top-left node.
21210
Nodes in graph labeled with their distance from the top-left node (Node(0)).
And just like binary trees, the BFS algorithm can be extended to know when we have finished processing all nodes at a level. We can do this by adding a for-loop that iterates over the size of the queue at the beginning of each level.

Adjacency List Level-By-Level

Solution
Python
Language
from collections import deque
def bfs_levels(graph, start):
queue = deque([start])
visited = set()
visited.add(start)
levels = []
while queue:
level_size = len(queue)
current_level = []
for _ in range(level_size):
node = queue.popleft()
current_level.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# IMPORTANT
# we have finished processing all nodes at the current level
levels.append(current_level)
return levels

Matrix Level-By-Level

Solution
Python
Language
from collections import deque
def bfs_level_by_level(matrix):
rows, cols = len(matrix), len(matrix[0])
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# start at the top-left corner
queue = deque([(0, 0)])
visited = set([(0, 0)])
levels = []
while queue:
level_size = len(queue)
current_level = []
for _ in range(level_size):
row, col = queue.popleft()
current_level.append((row, col))
for dr, dc in directions:
r, c = row + dr, col + dc
if 0 <= r < rows and 0 <= c < cols and (r, c) not in visited:
visited.add((r, c))
queue.append((r, c))
# IMPORTANT
# we have finished processing all nodes at this level
levels.append(current_level)
return levels

Shortest Path in a Graph

A consequence of the level-by-level nature of BFS traversal is that we can use it to find the shortest path between two nodes in a graph. Because BFS traverses the graph level-by-level, the first time we reach the destination node will be on the shortest path between the two nodes.
The animation below shows how BFS finds the shortest path between the top left node in the matrix and the first node with value "1":
Visualization
0000001000000000

0 / 8

Compare this to depth-first search, where the first path it encounters might not be the shortest path between two nodes:
Visualization
0000001000000000

simple matrix DFS traversal

0 / 19

To find the shortest path using DFS, we would have to explore all possible paths and then compare the lengths of each path to find the shortest one at the end. This makes BFS a better choice for any question that involves finding the shortest path between two nodes in a graph.

Mark as read

Next: Minimum Knight Moves

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

BFS on an Adjacency List

BFS on an Matrix (2D Grid)

Nodes at a Level

Adjacency List Level-By-Level

Matrix Level-By-Level

Shortest Path in a Graph

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress