Dsa
Graphs Bfs
Easy
Shortest Path in City Blocks
You are given a grid representing streets in a city where each cell contains either '0' (open street) or '1' (building). You start from the top-left corner (0,0) and want to reach the bottom-right corner (n-1,m-1) by moving only along open streets. Find the shortest path in terms of the number of moves required. If no path exists, return -1.
Input:
The first line contains two integers n and m (1 <= n, m <= 1000), the dimensions of the grid.
The following n lines each contain m characters ('0' or '1').
Output:
An integer representing the shortest path length or -1 if no path exists.
Example:
Input:
3 3
0 1 0
0 0 0
1 0 0
Output:
4
Key concepts
graphsbfsshortest path
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now