Program to detect cycles in 2D grid in Python

PythonServer Side ProgrammingProgramming

Suppose we have one 2D array of characters called grid of size m x n. We have to check whether we can detect a cycle inside it or not. Here a cycle is a path of length 4 or more in the grid that starts and ends at the same position. We can move in four directions (up, down, left, or right), if it has the same value of the current cell, and we cannot revisit some cell.

So, if the input is like

mmmp
mkmm
mmsm
ftmm

then the output will be True, because the green cells are forming cycle.

To solve this, we will follow these steps −

  • WHITE := 0, GRAY := 1, BLACK := 2

  • R := row count of grid

  • C := column count of grid

  • color := an empty map, whose default value is 0

  • Define a function dfs() . This will take r, c, pr:= -1,pc:= -1

  • color[r,c] := GRAY

  • for each pair (x,y) in di, do

    • (nr,nc) := (r+x,c+y)

    • if 0 <= nr < R and 0 <= nc < C and grid[r, c] is same as grid[nr, nc] and (nr, nc) is not same as (pr, pc), then

      • if color[nr,nc] is same as WHITE, then

        • if dfs(nr,nc,r,c) is true, then

          • return True

        • otherwise when color[nr,nc] is same as GRAY, then

          • return True

      • color[r,c] := BLACK

      • return False

      • From the main method, do the following

      • for r in range 0 to R - 1, do

        • for c in range 0 to C - 1, do

          • if color[r,c] is same as WHITE, then

            • if dfs(r,c) is true, then

              • return True

  • return False

Example

Let us see the following implementation to get better understanding

from collections import defaultdict
di = [(0,1),(1,0),(0,-1),(-1,0)]
def solve(grid):
   WHITE,GRAY,BLACK = 0 ,1 ,2
   R,C = len(grid),len(grid[0])

   color = defaultdict(int)

   def dfs(r,c,pr=-1,pc=-1):
      color[r,c] = GRAY
      for x,y in di:
         nr,nc = r+x,c+y
         if (0<=nr<R and 0<=nc<C and grid[r][c] == grid[nr][nc] and (nr,nc)!=(pr,pc)):
            if color[nr,nc]==WHITE:
               if dfs(nr,nc,r,c):
                  return True
            elif color[nr,nc] == GRAY:
               return True

      color[r,c] = BLACK
      return False

   for r in range(R):
      for c in range(C):
         if color[r,c] == WHITE:
            if dfs(r,c):
               return True
   return False
matrix = [["m","m","m","p"],["m","k","m","m"],["m","m","s","m"],["f","m","m","m"]]
print(solve(matrix))

Input

7, [5,1,4,3]

Output

True
raja
Updated on 06-Oct-2021 09:27:24

Advertisements