![]() |
VOOZH | about |
Given a 2D matrix maze[][], where some cells are blocked, some cells are locked (which the rats can unlock) and some cells are vacant. Given the initial position of two rats, find the minimum number of cells they need to unlock to escape the maze. A rat can escape the maze if it reaches outside the boundary of the maze. Blocked cells are represented by '*', locked cells are represented by '#', vacant cells are represented by '.', and the initial position of rats is represented by '$'. A path from the outside to that rat is guaranteed to exist for each rat.
Note: If a rat unlocks a cell, it remains unlocked. A rat cannot pass through blocked cells and can pass through locked cells after unlocking them. Add images to represent the problem.
Example:
Input: n = 5, m = 9,
inputMaze[5][10] = { ****#****
*..#.#..*
****.****
*$#.#.#$*
*********}
Output: 4Input: n = 5, m = 11
inputMaze = {*#*********
*$*...*...*
*$*.*.*.*.*
*...*...*.*
*********.*}
Output: 0
Approach:
The idea is to first initializes distances from the outside boundary and rats' initial positions using breadth-first search (BFS). It then identifies and stores the positions of the locked cells. The BFS is performed for each rat separately, updating distances and considering the unlocking of doors. The final answer is calculated by adding the distances of both rats and the initial distances, adjusting for the unlocking of shared doors. The result represents the minimum number of cells that both rats need to unlock to escape the maze.
Steps:
Below is the implementation of the above approach:
4
Time complexity: O(N * M), where N is the number of rows and M is the number of columns in the maze. The primary factor contributing to this complexity is the breadth-first search (BFS) operation, which explores the maze cells.
Auxiliary Space : O(N * M), where N is the number of rows and M is the number of columns in the maze.