Given a maze in the form of a rectangular matrix, filled with either O, X, or M, where O represents an open cell, X represents a blocked cell, and M represents landmines in the maze, find the shortest distance of every open cell in the maze from its nearest mine.

We are only allowed to travel either of the four directions, and diagonal moves are not allowed. We can assume cells with the mine have distance 0. Also, blocked and unreachable cells have distance -1.

 
For example,

Input: 6 × 5 matrix filled with O (Open cell), X (Blocked Cell), and M (Landmine).
 
O   M   O   O   X
O   X   X   O   M
O   O   O   O   O
O   X   X   X   O
O   O   M   O   O
O   X   X   M   O
 
Output:
 
1   0   1   2  -1
2  -1  -1   1   0
3   4   3   2   1
3  -1  -1  -1   2
2   1   0   1   2
3  -1  -1   0   1

Practice this problem

The idea is to perform a BFS to solve this problem. Start by creating an empty queue and enqueue all cells with the mines. Then loop through the queue and consider each of four adjacent cells of the front cell. Enqueue the adjacent cell (with updated distance) if it represents an open space, and its distance from the mine is yet to be calculated. Repeat the procedure till the queue is empty.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

1   0   1   2  -1
2  -1  -1   1   0
3   4   3   2   1
3  -1  -1  -1   2
2   1   0   1   2
3  -1  -1   0   1

Java


Download  Run Code

Output:

[1, 0, 1, 2, -1]
[2, -1, -1, 1, 0]
[3, 4, 3, 2, 1]
[3, -1, -1, -1, 2]
[2, 1, 0, 1, 2]
[3, -1, -1, 0, 1]

Python


Download  Run Code

Output:

[1, 0, 1, 2, -1]
[2, -1, -1, 1, 0]
[3, 4, 3, 2, 1]
[3, -1, -1, -1, 2]
[2, 1, 0, 1, 2]
[3, -1, -1, 0, 1]

The time complexity of the proposed solution is O(M × N) and requires O(M × N) extra space, where M and N are dimensions of the matrix.

 
Author: Aditya Goel