Shortest Path in Binary Matrix

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2021-04-30

Problem Statement

Designing a pathfinding service that computes the shortest path from the top-left corner to the bottom-right corner of a binary matrix, where cells can either be blocked (1) or open (0).

The movement is allowed in 8 directions (horizontal, vertical, and diagonal), and the goal is to return the minimum number of steps required to reach the destination.


This service will be part of a larger platform (like a robot navigation system, AI grid simulation, or game engine) that frequently queries path computations in real time.


🎯 Problem Statement


Design a scalable and efficient system that:


•Accepts a binary matrix as input.
•Computes the shortest path length between two points (source to destination).
•Returns -1 if no valid path exists.


⚙️ Functional Requirements


Input:

•A 2D binary matrix grid[n][n].
•Each cell can be:
•0 → Open cell.
•1 → Blocked cell.
•Start = (0, 0), End = (n-1, n-1).

Output:

•Integer representing the length of the shortest path.
•Return -1 if no path exists.

Movement:

•Allowed in 8 directions (↖, ↑, ↗, ←, →, ↙, ↓, ↘).
•Each move has equal cost (1 step).

Example:

1 2Input: 3[[0,1], 4 [1,0]] 5 6Output: 2
1.Explanation: Path → (0,0) → (1,1)

Edge Cases:

•Start or end cell blocked → return -1.
•Single cell (0) → return 1.


🚫 Non-Functional Requirements


Aspect with Requirement


Latency

< 200 ms for grids up to 1000x1000


Scalability

Should handle multiple concurrent requests (batch jobs or API calls)


Accuracy

Must always return the correct minimum path length


Availability

99.9% uptime for real-time systems


Extensibility

Should support additional constraints (e.g., weighted cells, dynamic grids)


🧩 Key Design Components


1. Pathfinding Service


•Exposes an API endpoint:
1 2POST /path/shortest
•Request:
1 2{ 3 "grid": [[0,1,0],[0,0,0],[1,0,0]] 4}
•Response:
1 2{ 3 "shortest_path": 4 4}


2. Pathfinding Engine


•Implements Breadth-First Search (BFS) or optimized A* Search Algorithm.
•For large grids, distributed computation (e.g., divide into sub-grids).


3. Task Queue / Job Scheduler


•Handles multiple path computations concurrently.
•Supports asynchronous requests for large grid analysis.


4. Cache Layer (Redis / Memcached)


•Stores frequently requested grid computations (memoization).
•Useful for repeated path queries in similar maps.


5. Metrics & Monitoring


•Logs average computation time, cache hit/miss ratio.
•Alerts on computation latency or system overload.


🧠 Algorithm Design Notes


BFS is used since:

•Equal edge weights.
•Finds the shortest path in unweighted graphs.

Optimization Techniques:

•Early termination once destination is reached.
•Skip already visited or blocked cells.
•Parallel exploration for large grids (multi-threaded BFS).


🧱 System Architecture Overview

1 2[Client / API Gateway] 3 | 4 v 5[Shortest Path Service] -- calls --> [Pathfinding Engine] 6 | | 7 |-----------------> [Cache Layer] <--| 8 | 9 +--> [Job Queue] --> [Worker Nodes] 10 | 11 +--> [Metrics/Logging System]


🧩 Data Flow Example


1.Client sends POST request with grid.
2.API Gateway forwards it to Shortest Path Service.
3.Service checks Cache Layer for previous computation.
4.If not cached:
•Dispatch to Pathfinding Engine (BFS/A*).
•Computes and returns shortest path length.
•Stores result in cache for reuse.
5.Response returned to client with minimal latency.


📈 Scalability Enhancements


•Batch Request Handling: Compute multiple paths in parallel.
•Dynamic Sharding: Split huge grids for distributed computation.
•Cache Precomputation: For static or recurring grid structures.
•Async API: For long-running jobs.


🧮 Example Metrics


| Metric | Target


| Avg Latency | < 200 ms for 1000×1000 grid

| Max Grid Size | 5000×5000

| Throughput | 1000 requests/sec

| Cache Hit Rate | > 70%



💬 Interview Prompt (Final Form)

Design a Shortest Path Computation Service in a Binary Matrix.
The service should take a binary matrix as input, where 0s represent open cells and 1s represent blocked cells, and return the minimum number of steps required to reach from the top-left to the bottom-right corner, moving in 8 directions.
The system should be designed for scalability, low latency, and concurrent path computation.


Solution

Comments