# Minimum number of moves to escape maze matrix in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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[0])
q = [(0, 0, 1)] if not matrix[0][0] else []
matrix[0][0] = 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 12:57:28