高级农民
- 积分
- 4019
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-1-22
- 最后登录
- 1970-1-1
|
LC. 1559. Detect Cycles in 2D Grid
Solved
Medium
Topics
conpanies icon
Companies
Hint
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.
- import sys
- class Solution:
- def containsCycle(self, grid: List[List[str]]) -> bool:
- # 1. 应对大规模网格,Python 必须增加递归深度限制
- sys.setrecursionlimit(300000)
-
- nrows, ncols = len(grid), len(grid[0])
- visited = [[False] * ncols for _ in range(nrows)]
- def DFS(r, c, pr, pc):
- visited[r][c] = True
-
- for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
- nr, nc = r + dr, c + dc
-
- # 越界判断 & 字符相同判断
- if 0 <= nr < nrows and 0 <= nc < ncols and grid[nr][nc] == grid[r][c]:
- # 关键点 1:如果是父节点,直接跳过
- if (nr, nc) == (pr, pc):
- continue
-
- # 关键点 2:如果邻居已经访问过,且不是父节点 -> 发现环!
- if visited[nr][nc]:
- return True
-
- # 关键点 3:继续递归,如果递归深处发现了环,立即向上返回 True
- if DFS(nr, nc, r, c):
- return True
-
- return False
-
- for i in range(nrows):
- for j in range(ncols):
- if not visited[i][j]:
- if DFS(i, j, -1, -1):
- return True
-
- return False
复制代码 或者用 set 判断 vistied- from typing import List
- class Solution:
- def containsCycle(self, grid: List[List[str]]) -> bool:
- nrows, ncols = len(grid), len(grid[0])
- visited = set() # 使用 set 或二维数组均可,set 在 Python 中很常用
- def hasCycle(r, c, pr, pc):
- visited.add((r, c))
-
- for dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):
- nr, nc = r + dr, c + dc
-
- # 1. 边界检查 & 字符匹配
- if 0 <= nr < nrows and 0 <= nc < ncols and grid[nr][nc] == grid[r][c]:
- # 2. 关键:不能走回头路
- if (nr, nc) == (pr, pc):
- continue
-
- # 3. 核心:如果遇到已访问节点,说明绕了一圈回来了
- if (nr, nc) in visited:
- return True
-
- # 4. 递归探索,只有发现 True 时才向上返回
- if hasCycle(nr, nc, r, c):
- return True
-
- return False
-
- # 遍历所有起点
- for i in range(nrows):
- for j in range(ncols):
- if (i, j) not in visited:
- if hasCycle(i, j, -1, -1):
- return True
-
- return False
复制代码 |
|