Program to find out the shortest path to reach the goal in Python


Suppose, we are given a grid where the cells contain various symbols such as 'X', 'O', '*' and '#' and the symbols have various meanings.

  • '#' is the goal cell that we want to reach.
  • 'O' is a free cell via which we can travel to the goal cell.
  • '*' is our position in the cell.
  • 'X' is a blocked cell, via which we cannot travel.

We have to find out the number of moves required to reach the goal cell from our current position in the grid. If the goal is not reachable, we return -1. The grid is given as input to the program.

So, if the input is like

XXOX
XX*X
X#OX
XXXX

then the output will be 2

To solve this, we will follow these steps −

  • m := row count of grid
  • n := column count of grid
  • for i in range 0 to m, do
    • for j in range 0 to n, do
      • if grid[i, j] is same as "*", then
        • come out from the loop
      • otherwise,
        • go for the next iteration
      • come out from the loop
  • ans := 0
  • queue := a new list containing integer pair (i, j)
  • grid[i, j] := "X"
  • while queue is not empty, do
    • ans := ans + 1
    • newq := a new list
    • for each i, j in queue, do
      • for each ii, jj in(i-1, j) ,(i, j-1) ,(i, j+1) ,(i+1, j), do
        • if 0 <= ii < m and 0 <= jj < n and grid[ii, jj] is not same as "X", then
          • if grid[ii, jj] is same as "#", then
            • return ans
          • insert ii, jj at the end of newq
          • grid[ii, jj] := "X"
    • queue := newq
  • return -1

Example

Let us see the following implementation to get better understanding −

def solve(grid):
   m, n = len(grid), len(grid[0])
   for i in range(m):
      for j in range(n):
         if grid[i][j] == "*": break
      else: continue
      break
   ans = 0
   queue = [(i, j)]
   grid[i][j] = "X"
   while queue:
      ans += 1
      newq = []
      for i, j in queue:
         for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
            if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] != "X":
               if grid[ii][jj] == "#": return ans
               newq.append((ii, jj))
               grid[ii][jj] = "X"
      queue = newq
   return -1

print(solve([['X', 'X', 'O', 'X'],['X', 'X', '*', 'X'],['X', '#',
'O', 'X'],['X', 'X', 'X', 'X']]))

Input

[['X', 'X', 'O', 'X'],
['X', 'X', '*', 'X'],
['X', '#', 'O', 'X'],
['X', 'X', 'X', 'X']]

Output

2

Updated on: 06-Oct-2021

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements