Leetcode 1559: Detect Cycles in 2D Grid

grid47
grid47
Exploring patterns and algorithms
Jun 4, 2024 7 min read

Given a 2D grid of characters, find if there exists a cycle where the same character repeats in the grid. A cycle is defined as a path where a character appears 4 or more times, forming a loop that starts and ends at the same cell. The cycle must consist of adjacent cells, and you are not allowed to revisit the previous cell.
Problem
Approach
Steps
Complexity
Input: The input consists of a 2D array of characters representing the grid, where the size of the grid is m x n. The grid only contains lowercase English letters.
Example: Input: grid = [['a', 'b', 'a'], ['b', 'a', 'b'], ['a', 'b', 'a']]
Constraints:
• 1 <= m, n <= 500
• grid consists only of lowercase English letters
Output: Return true if there is a cycle of the same character in the grid, otherwise return false.
Example: Output: true
Constraints:
Goal: We need to identify if there exists a cycle in the grid where a character repeats in a loop of 4 or more cells.
Steps:
• Iterate through all cells in the grid.
• For each unvisited cell, perform a depth-first search (DFS) to find a cycle of the same character.
• Keep track of the previous cell to avoid revisiting it in the next step.
• If a cycle is found, return true, else continue to the next cell.
• Return false if no cycle is found.
Goal: The grid is a 2D array with a size of m x n, where both m and n are between 1 and 500. All cells contain lowercase letters.
Steps:
• 1 <= m, n <= 500
• grid consists only of lowercase English letters
Assumptions:
• A cycle must consist of at least 4 cells.
• The cycle must only consist of adjacent cells in one of four directions (up, down, left, right).
Input: Example 1: grid = [['a', 'a', 'a', 'a'], ['a', 'b', 'b', 'a'], ['a', 'b', 'b', 'a'], ['a', 'a', 'a', 'a']]
Explanation: There are two valid cycles in the grid: one cycle in the top-left corner and another one in the bottom-right corner.

Input: Example 2: grid = [['a', 'b', 'a'], ['b', 'a', 'b'], ['a', 'b', 'a']]
Explanation: There is no valid cycle in this grid as the characters don't form a loop of length 4 or more.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus