711088. Shortest Distance in a Binary Maze

Medium

Shortest Distance in a Binary Maze

Summary

In this problem, we are given a binary maze represented as an adjacency matrix. The goal is to find the shortest distance between two cells in the maze. This problem involves graph traversal and optimization techniques.

Detailed Explanation

To solve this problem, we can use Breadth-First Search (BFS) algorithm. BFS is particularly well-suited for finding the shortest path in a graph because it explores all the nodes at a given depth before moving on to the next level.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty queue and add the starting cell to it.
  2. While the queue is not empty:
    • Dequeue the front cell and mark it as visited.
    • For each unvisited neighbor of the dequeued cell, calculate its distance from the starting cell and enqueue it if the calculated distance is less than the current shortest distance to that neighbor.
  3. Once the queue is empty, return the shortest distance found for the target cell.

The time complexity of this algorithm is O(V + E), where V is the number of cells in the maze and E is the number of edges (neighbor relationships). The space complexity is also O(V) because we need to store the visited status of each cell.

Optimized Solutions

Here are optimized solutions for the problem:

Java

View on GeeksforGeeks
import java.util.*;

public class ShortestDistanceInBinaryMaze {
    public static int shortestDistance(int[][] maze, int startRow, int startCol, int targetRow, int targetCol) {
        if (maze == null || maze.length == 0 || maze[0].length == 0)
            return -1;

        int rows = maze.length;
        int cols = maze[0].length;
        boolean[][] visited = new boolean[rows][cols];
        int[] directions = {-1, 0, 1, 0, 0, 1}; // up, left, down, right
        int queueSize = 0;
        int[] queue = new int[4 * (rows + cols)];
        int startCellIndex = startRow * cols + startCol;
        int targetCellIndex = targetRow * cols + targetCol;

        visited[startRow][startCol] = true;
        int level = 0, index = 0;
        queue[index++] = startCellIndex;
        queueSize++;

        while (queueSize > 0) {
            for (int i = 0; i < queueSize; i++) {
                int cellIndex = queue[i];
                if (cellIndex == targetCellIndex)
                    return level;

                int row = cellIndex / cols;
                int col = cellIndex % cols;

                for (int j = 0; j < 4; j++) {
                    int newRow = row + directions[j * 2];
                    int newCol = col + directions[j * 2 + 1];

                    if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols
                            && !visited[newRow][newCol] && maze[newRow][newCol] == 1) {
                        visited[newRow][newCol] = true;
                        queue[index++] = newRow * cols + newCol;
                        queueSize++;
                    }
                }

            }
            level++;
        }

        return -1; // target cell not found
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.