Code, in Python
from typing import Set, Tuple
def is_pattern_contained_in_grid(grid, S):
def traverse(x, y, s_idx, visited: Set[Tuple[int,int]]):
if (s_idx == len(S)):
return True
if ((x, y) in visited
or not( x >= 0 and y >= 0 and x < n and y < m)
or grid[x][y] != S[s_idx]):
return False
for adj_x, adj_y in ((x + 1, y),
(x - 1, y),
(x, y + 1),
(x, y - 1)):
if (traverse(adj_x, adj_y, s_idx + 1, visited.union({(x,y)}))):
return True
return False
if (not S):
return True
n = len(grid)
m = len(grid[0])
for i in range(n*m):
x = i % n
y = i // n
if (traverse(x, y, 0, set())):
return True
return False
# Some examples
print(is_pattern_contained_in_grid([[0,0,0,0],[0,1,3,1],[0,3,4,0],[1,5,6,7]], [1,5,3,1,3,1]))
print(is_pattern_contained_in_grid([[0,0,0,0],[0,1,3,7],[0,3,4,0],[1,5,6,7]], [1,5,3,1,3,1]))
print(is_pattern_contained_in_grid([[0,0,0,0],[0,1,3,1],[0,3,4,0],[1,5,6,7]], [1,5,3,5,6]))