Bird
Raised Fist0
Interview Prepgraphs-dfs-bfsmediumAmazonGoogleFacebook

Shortest Path in Binary Matrix

Choose your preparation mode4 modes available
</>
IDE
def shortestPathBinaryMatrix(grid: List[List[int]]) -> int:public int shortestPathBinaryMatrix(int[][] grid)int shortestPathBinaryMatrix(vector<vector<int>>& grid)function shortestPathBinaryMatrix(grid)
def shortestPathBinaryMatrix(grid):
    # Write your solution here
    pass
class Solution {
    public int shortestPathBinaryMatrix(int[][] grid) {
        // Write your solution here
        return -1;
    }
}
#include <vector>
using namespace std;

int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
    // Write your solution here
    return -1;
}
function shortestPathBinaryMatrix(grid) {
    // Write your solution here
    return -1;
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: -1 when path existsNot considering diagonal moves or incorrectly marking visited cells.✅ Include all 8 directions in neighbor exploration and mark visited cells when enqueued.
Wrong: Path length longer than shortestUsing greedy approach instead of BFS, leading to suboptimal path.✅ Implement BFS level order traversal to guarantee shortest path.
Wrong: Crash or exception on empty gridNo check for empty input before processing.✅ Add explicit check for empty grid and return -1 immediately.
Wrong: TLE on large inputsUsing DFS/backtracking exponential approach instead of BFS.✅ Use BFS with queue and visited set for O(n^2) time complexity.
✓
Test Cases
t1_01basic
Input{"grid":[[0,1],[1,0]]}
Expected2

The shortest path is (0,0) → (1,1) diagonally, length 2.

t1_02basic
Input{"grid":[[0,0,0],[1,1,0],[1,1,0]]}
Expected5

Shortest path is (0,0) → (0,1) → (0,2) → (1,2) → (2,2), length 5 steps.

t2_01edge
Input{"grid":[]}
Expected-1

Empty grid means no path exists, return -1.

t2_02edge
Input{"grid":[[0]]}
Expected1

Single cell grid with 0 means start=end, path length is 1.

t2_03edge
Input{"grid":[[1]]}
Expected-1

Single cell grid blocked means no path, return -1.

t2_04edge
Input{"grid":[[0,0],[0,0]]}
Expected2

Small grid with all zeros; shortest path is diagonal (0,0) → (1,1), length 2.

t3_01corner
Input{"grid":[[0,0,0],[0,1,0],[0,0,0]]}
Expected4

Shortest path avoids blocked center cell using diagonals, length 4.

t3_02corner
Input{"grid":[[0,0,0,0],[1,1,1,0],[0,0,0,0],[0,1,1,1],[0,0,0,0]]}
Expected8

Path requires careful BFS to navigate around blocked cells, length 8.

t3_03corner
Input{"grid":[[0,1,0],[1,0,1],[0,1,0]]}
Expected-1

No path exists due to blocking pattern, return -1.

t4_01performance
Input{"grid":[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],[0,0,0,0,0,0,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,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]}
⏱ Performance - must finish in 2000ms

n=100 grid with alternating blocked rows; BFS O(n^2) must complete within 2s.

Practice

(1/5)
1. Given the following Python code implementing the two-pass DP solution for the 01 Matrix problem, what is the final distance matrix returned for input [[0,1,1],[1,1,0],[1,1,1]]?
easy
A. [[0,1,1],[1,1,0],[2,1,1]]
B. [[0,1,2],[1,1,0],[2,1,1]]
C. [[0,1,1],[1,2,0],[2,1,1]]
D. [[0,1,1],[1,1,0],[1,1,1]]

Solution

  1. Step 1: Initialize distances

    Set dist to 0 where mat is 0, else infinity: [[0,inf,inf],[inf,inf,0],[inf,inf,inf]]
  2. Step 2: Forward pass updates

    Update dist using top and left neighbors: [[0,1,2],[1,2,0],[2,3,1]]
  3. Step 3: Backward pass updates

    Update dist using bottom and right neighbors: [[0,1,2],[1,1,0],[2,1,1]]
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Distances match shortest paths to nearest zero [OK]
Hint: Two-pass DP updates distances from neighbors correctly [OK]
Common Mistakes:
  • Off-by-one in indices
  • Forgetting backward pass
  • Incorrect initialization
2. Consider the following Python code implementing the Bellman-Ford algorithm for the Network Delay Time problem. Given the input times = [[1,2,1],[2,3,2],[1,3,4]], n = 3, and k = 1, what is the final returned value?
easy
A. 4
B. 3
C. 2
D. -1

Solution

  1. Step 1: Initialize distances with dist[1]=0, dist[2]=inf, dist[3]=inf

    After first iteration, relax edges: dist[2]=1 (via 1->2), dist[3]=4 (via 1->3)
  2. Step 2: Second iteration relaxes edge 2->3: dist[3] updated to dist[2]+2=3 which is less than 4

    No further updates after this iteration, so loop breaks early
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Maximum distance is 3, so return 3 [OK]
Hint: Relax edges repeatedly until no updates or n-1 iterations [OK]
Common Mistakes:
  • Not updating dist[3] to 3 after second iteration
  • Returning initial max distance 4 instead of updated 3
  • Confusing iteration count and stopping early
3. You are given a 2D grid map of '1's (land) and '0's (water). You need to count the number of distinct islands, where an island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. Which algorithmic approach guarantees an optimal solution to this problem?
easy
A. Use Depth-First Search (DFS) or Breadth-First Search (BFS) to traverse connected components in the grid.
B. Use a sorting-based approach to group land cells and count islands.
C. Use Dynamic Programming to store intermediate island counts for subgrids.
D. Use a greedy approach to count islands by scanning rows and columns independently.

Solution

  1. Step 1: Understand the problem as finding connected components in a grid

    The problem requires identifying groups of adjacent '1's connected horizontally or vertically, which is a classic graph traversal problem.
  2. Step 2: Recognize that DFS or BFS traversals efficiently explore connected components

    DFS or BFS starting from each unvisited land cell will mark all connected land cells as visited, ensuring each island is counted exactly once.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    DFS/BFS is the standard approach for connected components in grids [OK]
Hint: Islands = connected components -> use DFS/BFS [OK]
Common Mistakes:
  • Thinking greedy or sorting can identify islands correctly.
4. Consider the following Python code implementing bidirectional BFS for the Word Ladder problem. Given beginWord = "hit", endWord = "cog", and wordList = ["hot", "dot", "dog", "lot", "log", "cog"], what is the returned value?
easy
A. 4
B. 5
C. 6
D. 0

Solution

  1. Step 1: Trace initial sets and level

    begin_set = {"hit"}, end_set = {"cog"}, level = 1
  2. Step 2: Expand begin_set neighbors and check for intersection

    Level 2: neighbors of "hit" include "hot"; no intersection yet. Level increments to 2.
  3. Step 3: Expand smaller frontier each iteration until intersection

    Level 3: from "hot" neighbors "dot", "lot"; still no intersection. Level 4: from "dot", "lot" neighbors "dog", "log"; next level neighbors include "cog" which is in end_set, so return level + 1 = 4.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Shortest transformation length is 4 steps [OK]
Hint: Bidirectional BFS returns shortest path length 4 [OK]
Common Mistakes:
  • Off-by-one in level counting
  • Not updating visited correctly
  • Returning 0 if endWord missing
5. Suppose the flood fill problem is modified so that pixels can be recolored multiple times if they become connected again after recoloring neighbors (e.g., due to dynamic color changes). Which modification to the algorithm is necessary to handle this correctly?
hard
A. Implement a queue-based BFS with a visited set to track pixels to recolor multiple times safely
B. Remove the early exit check for original_color == newColor to allow recoloring cycles
C. Use a visited set to prevent recoloring any pixel more than once
D. Allow recoloring pixels multiple times without tracking visited, relying on recursion depth

Solution

  1. Step 1: Understand the problem variant

    Pixels can be recolored multiple times if connectivity changes dynamically, so simple DFS with early exit is insufficient.
  2. Step 2: Choose an approach that tracks pixels safely

    BFS with a visited set can manage dynamic recoloring by controlling which pixels are processed and preventing infinite loops.
  3. Step 3: Explain why other options fail

    Use a visited set to prevent recoloring any pixel more than once disallows multiple recolors, B removes necessary early exit causing infinite loops, D risks infinite recursion without control.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    BFS with visited set handles dynamic recoloring safely [OK]
Hint: Dynamic recoloring needs careful tracking with BFS and visited set [OK]
Common Mistakes:
  • Removing early exit causes infinite loops
  • Ignoring visited set leads to stack overflow
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard