Lesson overview · Free interview practice

Graph BFS

Traverse graphs using Breadth-First Search.

Topics in the full lesson
  • Concept and Use Cases
  • When to Use
  • Time and Space Complexity
  • Graph BFS for Finding Shortest Path
  • Finding Connected Components in an Undirected Graph
  • Detecting Cycles in an Undirected Graph
  • Finding the Shortest Path in an Unweighted Graph

Practice Problems

Work through a question before revealing its explanation. These questions and answers are free; Premium adds the full lesson walkthrough, examples and implementation detail.

Completion marks record your own progress, not an automatically checked result. The task type does not determine whether it is optional.

Question

Given an n x n binary matrix grid, return the length of the shortest clear path from the top-left cell (0, 0) to the bottom-right cell (n - 1, n - 1), or -1 if no such path exists. A clear path visits only cells with value 0 and may move in any of the 8 directions; its length is the number of cells visited.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Question

On an infinite chessboard, a knight begins at (0, 0). A knight moves two squares along one axis and then one square along the perpendicular axis. Given a target square (x, y), return the minimum number of moves needed to reach it.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

CodingMedium

Open the Lock

Question

You have a lock with 4 circular wheels, each with digits 09. The lock starts at '0000'. Each move turns one wheel by one slot (e.g., '1''2' or '1''0'). Given a list of deadends (lock states you must avoid) and a target combination, return the minimum number of moves to reach target, or -1 if impossible.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Explore the full Graph BFS material

Premium includes the complete lessons and implementation references. Free practice questions remain available without a subscription.

All course tracks & premium content
From basics to advanced masterclasses
Built for JS/TS developers like you
Real-world tips & common pitfalls
Upgrade to Premium