Program to find minimum number of cells it will take to reach bottom right corner in Python

PythonServer Side ProgrammingProgramming

Suppose we have a 2D grid representing a maze where 0 is for empty space, and 1 is the wall. We will start at grid[0, 0], we have to find the minimum number of squares it would take to get to bottom right corner of the grid. If we cannot reach, return −1.

So, if the input is like

000
100
100

then the output will be 5

To solve this, we will follow these steps −

  • R := row count of grid, C := column count of grid

  • q := [0, 0, 1] when A[0, 0] is 1 otherwise a new list

  • A[0, 0] := 1

  • for each (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 x in range 0 to R and y in range 0 to C and A[x, y] is same as 0, then

          • A[x, y] := 1

          • insert (x, y, d + 1) at the end of q

  • return −1

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, A):
      R, C = len(A), len(A[0])
      q = [(0, 0, 1)] if not A[0][0] else []
      A[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 A[x][y] == 0:
               A[x][y] = 1
               q.append((x, y, d + 1))
      return −1
ob = Solution()
grid = [
   [0, 0, 0],
   [1, 0, 0],
   [1, 0, 0]
]
print(ob.solve(grid))

Input

grid = [ [0, 0, 0], [1, 0, 0], [1, 0, 0] ]

Output

5
raja
Published on 21-Oct-2020 12:03:47
Advertisements