Suppose we have a 2d matrix. We have to check whether we can start from some cell then move adjacent cells (up, down, left, right) of the same value, and come back to the same starting point. We cannot revisit a cell that we have visited last.
So, if the input is like
then the output will be True, as we can follow 2s to form a cycle.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, matrix): R = len(matrix) C = len(matrix) def get_neighbors(i, j): val = matrix[i][j] for ii, jj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)): if 0 <= ii < R and 0 <= jj < C and matrix[ii][jj] == val: yield ii, jj vis = [[False] * C for _ in range(R)] def dfs(root): stack = [(root, None)] vis[root][root] = True while stack: v, prev = stack.pop() for w in get_neighbors(*v): if w != prev: if not vis[w][w]: vis[w][w] = True stack.append((w, v)) else: return True return False for i in range(R): for j in range(C): if not vis[i][j]: if dfs((i, j)): return True return False ob = Solution() matrix = [ [2, 2, 2, 1], [2, 1, 2, 1], [2, 2, 2, 1] ] print(ob.solve(matrix))
[ [2, 2, 2, 1], [2, 1, 2, 1], [2, 2, 2, 1] ]