Find and Reconstruct a Binary-Matrix Path
Updated
Problem statement
You are given a non-empty rectangular binary matrix grid. A cell containing 0 is passable and a cell containing 1 is blocked.
Return a shortest path from the top-left cell [0,0] to the bottom-right cell [rows-1,cols-1]. Consecutive cells may move one step up, left, right, or down, and the path must contain only passable cells.
The returned array contains the coordinates in travel order, including both endpoints. If no path exists, return an empty array. If several shortest paths exist, return the lexicographically smallest coordinate sequence, comparing a coordinate by row and then column.
Function
shortestBinaryMatrixPath(grid: int[][]) → int[][]Examples
Example 1
grid = [[0,0,1],[1,0,0],[1,1,0]]return = [[0,0],[0,1],[1,1],[1,2],[2,2]]The displayed route is the only shortest path through passable cells.
Example 2
grid = [[0,0],[0,0]]return = [[0,0],[0,1],[1,1]]Both two-step routes are shortest. Moving right first produces the lexicographically smaller coordinate sequence.
Example 3
grid = [[0,1],[1,0]]return = []The two passable endpoints are disconnected by blocked cells.
Constraints
gridis non-empty and rectangular.- Every cell is either
0or1. - Coordinate sequences are compared lexicographically by
[row,column].
More Meta Phone Screen questions
- Convert a Sorted Linked List to a Balanced BSTPHONE SCREEN · Seen Nov 2026
- Fuzzy Word Lookup With One Misspelled LetterPHONE SCREEN · Seen Nov 2026
- Multi-Head Attention Forward PassPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Run-Length Encoded Vector Dot ProductPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Mutual-Friend RecommendationsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Time to Buy and Sell StockPHONE SCREEN · Seen Nov 2026
- First Element Greater Than KPHONE SCREEN · Seen Nov 2026
- Count Events in Rolling Minute WindowsPHONE SCREEN · Seen Oct 2026
- Valid Word AbbreviationPHONE SCREEN · Seen Oct 2026
- Shortest Path in a Binary MatrixPHONE SCREEN · Seen Sep 2026
Similar questions at other companies
- Shortest Increasing Path to a TargetUber · ONSITE INTERVIEW
- Shortest Distance from All BuildingsWaymo · PHONE SCREEN
- Fire Station Response BillLinkedIn · ONSITE INTERVIEW
- Number of Islands with Diagonal ConnectivityGoogle · ONSITE INTERVIEW
- Island Count and Maximum AreaOracle · ONSITE INTERVIEW
- Count Islands in a Binary GridApple · PHONE SCREEN
- Pacific Atlantic Water FlowAnduril · PHONE SCREEN
- Max Area of IslandGoldman Sachs · ONSITE INTERVIEW
- Max Area of IslandRoku · ONSITE INTERVIEW
- Maximum Damage PatchGecko Robotics · OA · PHONE SCREEN