给你一个二维字符网格数组 grid ,大小为 m x n ,你需要检查 grid 中是否存在 相同值 形成的环。
一个环是一条开始和结束于同一个格子的长度 大于等于 4 的路径。对于一个给定的格子,你可以移动到它上、下、左、右四个方向相邻的格子之一,可以移动的前提是这两个格子有 相同的值 。
同时,你也不能回到上一次移动时所在的格子。比方说,环 (1, 1) -> (1, 2) -> (1, 1) 是不合法的,因为从 (1, 2) 移动到 (1, 1) 回到了上一次移动时的格子。
如果 grid 中有相同值形成的环,请你返回 true ,否则返回 false 。
示例 1:
输入:grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]
输出:true
解释:如下图所示,有 2 个用不同颜色标出来的环:
示例 2:
输入:grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]
输出:true
解释:如下图所示,只有高亮所示的一个合法环:
示例 3:
输入:grid = [["a","b","b"],["b","z","b"],["b","b","a"]]
输出:false
提示:
m == grid.length
n == grid[i].length
1 <= m <= 500
1 <= n <= 500
grid 只包含小写英文字母。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/detect-cycles-in-2d-grid
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
第一种思路:
DFS + 回溯。会各种爆栈或者超时……
第二种思路:
并查集,对于每个点连它的左边或者上边,
如果本来就连上了说明有环,只要有环长度必定大于4。
如果本来没连上就把它俩连上。
时间复杂度:O(MN)
空间复杂度:O(MN)
class Solution(object):
def containsCycle(self, grid):
"""
:type grid: List[List[str]]
:rtype: bool
"""
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
ufs = UnionFindSet(grid)
m, n = len(grid), len(grid[0])
for i in range(m):
for j in range(n):
for next_i, next_j in [(i - 1, j), (i, j - 1)]: # 往上或者往左
if 0 <= next_i < m and 0 <= next_j < n and grid[next_i][next_j] == grid[i][j]:
if ufs.find(i * n + j) == ufs.find(next_i * n + next_j):
return True
else:
ufs.union(i * n + j, next_i * n + next_j)
return False
class UnionFindSet(object):
def __init__(self, grid):
m, n = len(grid), len(grid[0])
self.roots = [-1 for i in range(m*n)]
self.rank = [0 for i in range(m*n)]
self.count = 0
for i in range(m):
for j in range(n):
self.roots[i * n + j] = i * n + j
self.count += 1
def find(self, member):
tmp = []
while member != self.roots[member]:
tmp.append(member)
member = self.roots[member]
for root in tmp:
self.roots[root] = member
return member
def union(self, p, q):
parentP = self.find(p)
parentQ = self.find(q)
if parentP != parentQ:
if self.rank[parentP] > self.rank[parentQ]:
self.roots[parentQ] = parentP
elif self.rank[parentP] < self.rank[parentQ]:
self.roots[parentP] = parentQ
else:
self.roots[parentQ] = parentP
self.rank[parentP] -= 1
self.count -= 1