Shortest Path in a Binary Maze Problem Statement

Given a maze represented as a binary rectangular matrix of size M*N, where each element can either be 0 or 1, determine the length of the shortest path from a given source cell to a destination cell.

The path can only be traversed through a cell with a value of 1, and movement is possible in one of four directions at any moment. The valid moves are:

Up: (x, y) -> (x - 1, y) Left: (x, y) -> (x, y - 1) Down: (x, y) -> (x + 1, y) Right: (x, y) -> (x, y + 1)

If no path from the source to the destination exists, return -1.

Input:

The first line contains an integer ‘T’ representing the number of test cases.
For each test case:
The first line contains two integers M and N, representing the number of rows and columns.
The next M lines contain N integers each, representing the matrix.
The last second line contains two integers denoting the coordinates of the source.
The last line contains two integers denoting the coordinates of the destination.

Output:

For each test case, output a single integer representing the length of the shortest path from the source to the destination. If no path exists, output -1.

Example:

Input:
3 4
1 1 1 1
0 1 1 0
0 0 1 1
0 0
2 3
Output:
5
Explanation:

The binary matrix is 3 rows by 4 columns with a source at (0, 0) and a destination at (2, 3). The shortest path length is 5.

Constraints:

  • 1 <= T <= 10
  • 1 <= M, N <= 100
  • Time Limit: 1 sec
AnswerBot
4mo

Find the length of the shortest path in a binary maze from a given source to destination.

  • Use Breadth First Search (BFS) algorithm to find the shortest path in the binary maze.

  • Create a queue to store t...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Intern Interview Questions Asked at Samsung

Q. Suppose an array of length n sorted in ascending order is rotated between 1 and ...read more
Q. What are the ACID properties in DBMS?
Q. Sum of Digits Problem Statement Given an integer 'N', continue summing its digit...read more
Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits