Program to check some elements in matrix forms a cycle or not in python

A matrix cycle exists when we can start from a cell, move through adjacent cells with the same value, and return to the starting position without revisiting the previous cell. This problem uses depth-first search (DFS) to detect such cycles.

Problem Understanding

Given a 2D matrix, we need to check if we can form a cycle by moving through adjacent cells (up, down, left, right) that have the same value. The key constraint is that we cannot revisit the cell we just came from.

For example, consider this matrix ?

2 2 2 1
2 1 2 1
2 2 2 1

Here, the cells with value 2 form a cycle around the perimeter.

Algorithm Approach

We use DFS with a stack to traverse each connected component of same-valued cells. For each unvisited cell, we check if it can form a cycle ?

  • Start DFS from each unvisited cell
  • Track the previous cell to avoid immediate backtracking
  • If we reach a visited cell (that's not the previous cell), we found a cycle
  • Use a visited matrix to track explored cells

Implementation

class Solution:
    def solve(self, matrix):
        R = len(matrix)
        C = len(matrix[0])

        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[0]][root[1]] = True
            while stack:
                v, prev = stack.pop()
                for w in get_neighbors(*v):
                    if w != prev:
                        if not vis[w[0]][w[1]]:
                            vis[w[0]][w[1]] = 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

# Test the solution
ob = Solution()
matrix = [
    [2, 2, 2, 1],
    [2, 1, 2, 1],
    [2, 2, 2, 1]
]
print(ob.solve(matrix))
True

How It Works

The algorithm works as follows ?

  1. get_neighbors() - Finds all adjacent cells with the same value
  2. dfs() - Performs depth-first search using a stack, tracking the previous cell
  3. If we encounter a visited cell that's not our previous cell, we found a cycle
  4. We iterate through all cells, starting DFS from unvisited ones

Example with Different Matrix

# Test with a matrix that has no cycle
ob = Solution()
matrix_no_cycle = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print("Matrix with no cycle:", ob.solve(matrix_no_cycle))

# Test with a simple cycle
matrix_simple_cycle = [
    [1, 1],
    [1, 1]
]
print("Simple 2x2 cycle:", ob.solve(matrix_simple_cycle))
Matrix with no cycle: False
Simple 2x2 cycle: True

Time and Space Complexity

  • Time Complexity: O(R × C) where R and C are matrix dimensions
  • Space Complexity: O(R × C) for the visited matrix and recursion stack

Conclusion

This algorithm efficiently detects cycles in a matrix by using DFS with careful tracking of the previous cell. The key insight is that finding a visited cell (other than the previous one) indicates a cycle has been formed.

Updated on: 2026-03-25T13:10:55+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements