Skip to content

1559. Detect Cycles in 2D Grid

Description

Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.

A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. 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 value of the current cell.

Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.

Return true if any cycle of the same value exists in grid, otherwise, return false.

 

Example 1:

Input: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
Output: true
Explanation: There are two valid cycles shown in different colors in the image below:

Example 2:

Input: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
Output: true
Explanation: There is only one valid cycle highlighted in the image below:

Example 3:

Input: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
Output: false

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 500
  • grid consists only of lowercase English letters.

 

Solutions

Solution: Depth-First Search

  • Time complexity: O(mn)
  • Space complexity: O(mn)

 

JavaScript

js
/**
 * @param {character[][]} grid
 * @return {boolean}
 */
const containsCycle = function (grid) {
  const m = grid.length;
  const n = grid[0].length;
  const visited = new Set();
  const isCycle = (row, col, preRow, preCol, value) => {
    if (row < 0 || col < 0 || row >= m || col >= n) return false;
    const current = grid[row][col];
    if (current !== value) return false;
    if (visited.has(`${row}_${col}`)) return true;
    visited.add(`${row}_${col}`);

    for (const move of [1, -1]) {
      const moveRow = row + move;
      const moveCol = col + move;

      if (moveRow !== preRow && isCycle(moveRow, col, row, col, value)) return true;
      if (moveCol !== preCol && isCycle(row, moveCol, row, col, value)) return true;
    }
    return false;
  };

  for (let row = 0; row < m; row++) {
    for (let col = 0; col < n; col++) {
      if (visited.has(`${row}_${col}`)) continue;
      const value = grid[row][col];

      if (isCycle(row, col, -1, -1, value)) return true;
    }
  }
  return false;
};

Released under the MIT license