Shortest Distance in a Binary Maze

Graphs Shortest Path Algorithms Hard

Given an n x m matrix grid where each cell contains either 0 or 1, determine the shortest distance between a source cell and a destination cell. You can move to an adjacent cell (up, down, left, or right) if that adjacent cell has a value of 1. The path can only be created out of cells containing 1. If the destination cell is not reachable from the source cell, return -1.

Examples:

Input: grid = [[1, 1, 1, 1],[1, 1, 0, 1],[1, 1, 1, 1],[1, 1, 0, 0],[1, 0, 0, 1]], source = [0, 1], destination = [2, 2]

Output: 3

Explanation: The shortest path from (0, 1) to (2, 2) is:

Move down to (1, 1)

Move down to (2, 1)

Move right to (2, 2)

Thus, the shortest distance is 3

Input: grid = [[1, 1, 1, 1, 1],[1, 1, 1, 1, 1],[1, 1, 1, 1, 0],[1, 0, 1, 0, 1]], source = [0, 0], destination = [3, 4]

Output: -1

Explanation: 

Since, there is no path possible between the source cell and the destination cell, hence we return -1.

Input: grid = [[1, 0, 1],[1, 1, 0],[1, 1, 1]], source = [0, 0], destination = [2, 2]

Constraints

  • 1 ≤ n, m ≤ 500
  • grid[i][j] == 0 or grid[i][j] == 1
  • The source and destination cells are always inside the given matrix.

Hints

  • Check if either the source or destination cell is 0. If so, return -1 (impossible to reach). Use a queue for BFS traversal, storing (row, col, distance). Maintain a visited matrix to prevent cycles.
  • Process each cell, exploring its 4 valid neighbors (up, down, left, right), and update their distances if they are not visited and have value 1. If we reach the destination cell, return the current distance. If the queue is exhausted and the destination is not reached, return -1.

Company Tags

Seagate Technology Oracle Texas Instruments Robinhood Deloitte Riot Games Etsy Intel Electronic Arts Walmart NVIDIA Teladoc Health Instacart Siemens Healthineers Reddit Salesforce Western Digital Twilio Johnson & Johnson Snowflake Morgan Stanley McKinsey & Company Alibaba Red Hat American Express Google Microsoft Amazon Meta Apple Netflix Adobe