LeetCode 1559. Detect Cycles in 2D Grid Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
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 1: BFS

We can traverse each cell in the 2D grid. For each cell, if the cell grid[i][j] has not been visited, we start a breadth-first search (BFS) from that cell. During the search, we need to record the parent node of each cell and the coordinates of the previous cell. If the value of the next cell is the same as the current cell, and it is not the previous cell, and it has already been visited, then it indicates the presence of a cycle, and we return true. After traversing all cells, if no cycle is found, we return false.

The time complexity is O(m × n), and the space complexity is O(m × n). Here, m and n are the number of rows and columns of the 2D grid, respectively.

PythonJavaC++GoTypeScriptRustJavaScript
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m, n = len(grid), len(grid[0]) vis = [[False] * n for _ in range(m)] dirs = (-1, 0, 1, 0, -1) for i, row in enumerate(grid): for j, x in enumerate(row): if vis[i][j]: continue vis[i][j] = True q = [(i, j, -1, -1)] while q: x, y, px, py = q.pop() for dx, dy in pairwise(dirs): nx, ny = x + dx, y + dy if 0 <= nx < m and 0 <= ny < n: if grid[nx][ny] != grid[i][j] or (nx == px and ny == py): continue if vis[nx][ny]: return True vis[nx][ny] = True q.append((nx, ny, x, y)) return False(code-box)

Solution 2: DFS

We can traverse each cell in the 2D grid. For each cell, if the cell grid[i][j] has not been visited, we start a depth-first search (DFS) from that cell. During the search, we need to record the parent node of each cell and the coordinates of the previous cell. If the value of the next cell is the same as the current cell, and it is not the previous cell, and it has already been visited, then it indicates the presence of a cycle, and we return true. After traversing all cells, if no cycle is found, we return false.

The time complexity is O(m × n), and the space complexity is O(m × n). Here, m and n are the number of rows and columns of the 2D grid, respectively.

PythonJavaC++GoTypeScriptRust
class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: def dfs(x: int, y: int, px: int, py: int) -> bool: vis[x][y] = True for dx, dy in pairwise(dirs): nx, ny = x + dx, y + dy if 0 <= nx < m and 0 <= ny < n: if grid[nx][ny] != grid[x][y] or (nx == px and ny == py): continue if vis[nx][ny] or dfs(nx, ny, x, y): return True return False m, n = len(grid), len(grid[0]) vis = [[False] * n for _ in range(m)] dirs = (-1, 0, 1, 0, -1) for i in range(m): for j in range(n): if vis[i][j]: continue if dfs(i, j, -1, -1): return True return False(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !