# Minimum number of moves to escape maze matrix in Python

Suppose we have a binary matrix, where 0 is representing an empty cell, and 1 is a wall. If we start from top left corner (0, 0), we have to find the minimum number of cells it would take to get to bottom right corner (R-1, C-1) Here R is number of rows and C is number of columns. If we cannot find any answer, return -1.

So, if the input is like

 0 0 0 1 0 0 0 1 1 0 0 0 0 1 1 1 1 0 0 0

then the output will be 8 because, we can select path like −

 0 0 0 1 0 0 0 1 1 0 0 0 0 1 1 1 1 0 0 0

To solve this, we will follow these steps −

• R := number of rows
• C := number of columns
• q := an empty list, initially insert (0, 0, 1) if matrix[0, 0] is 0
• matrix[0, 0] := 1
• for each triplet (r, c, d) in q, do
• if (r, c) is same as (R - 1, C - 1), then
• return d
• for each x, y in [(r + 1, c) ,(r - 1, c) ,(r, c + 1) ,(r, c - 1) ], do
• if 0 <= x < R and 0 <= y < C and matrix[x, y] is same as 0, then
• matrix[x, y] := 1
• insert triplet (x, y, d + 1) at the end of q
• return -1

## Example

Let us see the following implementation to get better understanding −

def solve(matrix):
R, C = len(matrix), len(matrix)
q = [(0, 0, 1)] if not matrix else []
matrix = 1
for r, c, d in q:
if (r, c) == (R - 1, C - 1):
return d
for x, y in [(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)]:
if 0 <= x < R and 0 <= y < C and matrix[x][y] == 0:
matrix[x][y] = 1
q.append((x, y, d + 1))
return -1

matrix = [
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 1],
[1, 1, 0, 0, 0]
]
print(solve(matrix))

## Input

[
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 1],
[1, 1, 0, 0, 0]
]

## Output

8

Updated on: 18-Oct-2021

508 Views 