LeetCode 题解工作台

二维网格图中探测环

给你一个二维字符网格数组 grid ,大小为 m x n ,你需要检查 grid 中是否存在 相同值 形成的环。 一个环是一条开始和结束于同一个格子的长度 大于等于 4 的路径。对于一个给定的格子,你可以移动到它上、下、左、右四个方向相邻的格子之一,可以移动的前提是这两个格子有 相同的值 。 同时,…

category

5

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 图·搜索

bolt

答案摘要

我们可以遍历二维网格中的每一个格子,对于每一个格子,如果格子 未被访问过,我们就从该格子开始进行广度优先搜索,搜索过程中,我们需要记录每一个格子的父节点,以及上一个格子的坐标,如果下一个格子的值与当前格子的值相同,且不是上一个格子,并且已经被访问过,那么就说明存在环,返回 。遍历完所有格子后,如果没有找到环,返回 。 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二维字符网格数组 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 只包含小写英文字母。
lightbulb

解题思路

方法一:BFS

我们可以遍历二维网格中的每一个格子,对于每一个格子,如果格子 grid[i][j]grid[i][j] 未被访问过,我们就从该格子开始进行广度优先搜索,搜索过程中,我们需要记录每一个格子的父节点,以及上一个格子的坐标,如果下一个格子的值与当前格子的值相同,且不是上一个格子,并且已经被访问过,那么就说明存在环,返回 true\textit{true}。遍历完所有格子后,如果没有找到环,返回 false\textit{false}

时间复杂度 O(m×n)O(m \times n),空间复杂度 O(m×n)O(m \times n)。其中 mmnn 分别是二维网格的行数和列数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
speed

复杂度分析

指标
时间complexity is O(m _n) in the worst case because each cell is visited at most once in DFS. Space complexity is O(m_ n) for the visited matrix and recursion stack for DFS in a fully connected component.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They may emphasize handling the 'parent' to prevent invalid 2-cell backtracking.

  • question_mark

    Expect questions about time and space trade-offs for DFS versus BFS in grids.

  • question_mark

    They might probe how the solution scales when m and n approach 500.

warning

常见陷阱

外企场景
  • error

    Failing to track the parent cell can falsely detect a 2-cell back-and-forth as a cycle.

  • error

    Not iterating over all unvisited cells may miss cycles in disconnected areas.

  • error

    Reusing the visited matrix incorrectly can create false positives or miss valid cycles.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Detect cycles in a 3D grid of characters using the same DFS pattern extended to six directions.

  • arrow_right_alt

    Find cycles of arbitrary lengths with different movement rules like diagonal adjacency.

  • arrow_right_alt

    Return the actual cycle path instead of just true/false, using DFS path reconstruction.

help

常见问题

外企场景

二维网格图中探测环题解:图·搜索 | LeetCode #1559 中等