Detect Cycles in 2D Grid LeetCode solution in Python

1
class Solution:
2
def containsCycle(self, grid: List[List[str]]) -> bool:
3

4
def getNeighbours(row, col, char):
5
neighbours = []
6
if row > 0 and grid[row - 1][col] == char and not visited[row - 1][col]:
7
neighbours.append([row - 1, col])
8
if col > 0 and grid[row][col - 1] == char and not visited[row][col - 1]:
9
neighbours.append([row, col - 1])
10
if (
11
row < len(grid) - 1
12
and grid[row + 1][col] == char
13
and not visited[row + 1][col]
14
):
15
neighbours.append([row + 1, col])
16
if (
17
col < len(grid[0]) - 1
18
and grid[row][col + 1] == char
19
and not visited[row][col + 1]
20
):
21
neighbours.append([row, col + 1])
22
return neighbours
23

24
def dfs(row, col, char, cyclePresent):
25
if visited[row][col] or cyclePresent:
26
cyclePresent = True
27
return cyclePresent
28
visited[row][col] = True
29
neighbours = getNeighbours(row, col, char)
30
for r, c in neighbours:
31
cyclePresent = dfs(r, c, char, cyclePresent)
32
return cyclePresent
33

34
visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]
35
cyclePresent = False
36
for row in range(len(grid)):
37
for col in range(len(grid[0])):
38
if cyclePresent:
39
return True
40
if visited[row][col]:
41
continue
42
cyclePresent = dfs(row, col, grid[row][col], cyclePresent)
43

44
return cyclePresent

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0