Design Gurus Logo
Problem Challenge 3 (medium)

Problem Statement

You are given a 2D matrix containing different characters, you need to find if there exists any cycle consisting of the same character in the matrix.

A cycle is a path in the matrix that starts and ends at the same cell and has four or more cells. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same character value of the current cell.

Write a function to find if the matrix has a cycle.

Example 1

Input: matrix =

Image

Output: true

Explanation: The given matrix has a cycle as shown below:

Image

Example 2

Input: matrix =

Image

Output: true

Explanation: The given matrix has one cycle as shown below:

Image

Example 3

Input: matrix =

Output: false

Explanation: The given matrix has no cycle.

Image

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 500
  • matrix[i][j] is '0' or '1'.

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory