BFS on matrix
Last updated: August 2, 2025
Quick Overview
Implement a Breadth-First Search (BFS) algorithm to traverse a given 2D matrix, where each cell can either be a passable space (represented by 0) or an obstacle (represented by 1). Your function should return the shortest path length from the top-left corner to the bottom-right corner of the matrix, or -1 if there is no valid path.
OpenAI
August 2, 20250
3
4,283 solved
Implement a Breadth-First Search (BFS) algorithm to traverse a given 2D matrix, where each cell can either be a passable space (represented by 0) or an obstacle (represented by 1). Your function should return the shortest path length from the top-left corner to the bottom-right corner of the matrix, or -1 if there is no valid path.
This coding problem is frequently asked during Phone Screen at OpenAI. The interviewer is testing your ability to translate a problem into clean, working code while discussing time and space complexity. OpenAI expects candidates to write production-quality code, not just solve the puzzle.
What the Interviewer Expects
- Identify the correct data structure and algorithm for the problem
- Write clean, bug-free code with proper variable naming
- Analyze time and space complexity correctly
- Handle basic edge cases (empty input, single element)
- Communicate your thought process while coding
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Can you solve this iteratively instead of recursively (or vice versa)?
- How would your solution change if the input was sorted?
- What happens if the input contains duplicates?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
This problem requires us to find the shortest path in a grid (2D matrix) from the top-left corner to the bottom-right corner. The BFS (Breadth-First Search) algorithm is appropriate here because it ex...
Approach
- Initialization: Start by checking if the start (0,0) or end (n-1,m-1) positions are blocked (value 1). If so, return -1 immediately.
- Queue Setup: Create a queue to facilitate the BFS and...