LeetCode 题解工作台

有向图中最大颜色值

给你一个 有向图 ,它含有 n 个节点和 m 条边。节点编号从 0 到 n - 1 。 给你一个字符串 colors ,其中 colors[i] 是小写英文字母,表示图中第 i 个节点的 颜色 (下标从 0 开始)。同时给你一个二维数组 edges ,其中 edges[j] = [a j , b j…

category

6

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

困难 · 动态·规划

bolt

答案摘要

求出每个点的入度,进行拓扑排序。 定义一个二维数组 ,其中 表示从起点到 点,颜色为 的节点数目。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 动态·规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 有向图 ,它含有 n 个节点和 m 条边。节点编号从 0 到 n - 1 。

给你一个字符串 colors ,其中 colors[i] 是小写英文字母,表示图中第 i 个节点的 颜色 (下标从 0 开始)。同时给你一个二维数组 edges ,其中 edges[j] = [aj, bj] 表示从节点 aj 到节点 bj 有一条 有向边 。

图中一条有效 路径 是一个点序列 x1 -> x2 -> x3 -> ... -> xk ,对于所有 1 <= i < k ,从 xi 到 xi+1 在图中有一条有向边。路径的 颜色值 是路径中 出现次数最多 颜色的节点数目。

请你返回给定图中有效路径里面的 最大颜色值 。如果图中含有环,请返回 -1 。

 

示例 1:

输入:colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
输出:3
解释:路径 0 -> 2 -> 3 -> 4 含有 3 个颜色为 "a" 的节点(上图中的红色节点)。

示例 2:

输入:colors = "a", edges = [[0,0]]
输出:-1
解释:从 0 到 0 有一个环。

 

提示:

  • n == colors.length
  • m == edges.length
  • 1 <= n <= 105
  • 0 <= m <= 105
  • colors 只含有小写英文字母。
  • 0 <= aj, bj < n
lightbulb

解题思路

方法一:拓扑排序 + 动态规划

求出每个点的入度,进行拓扑排序。

定义一个二维数组 dpdp,其中 dp[i][j]dp[i][j] 表示从起点到 ii 点,颜色为 jj 的节点数目。

ii 点出发,遍历所有出边 iji \to j,更新 dp[j][k]=max(dp[j][k],dp[i][k]+(c==k))dp[j][k] = \max(dp[j][k], dp[i][k] + (c == k)),其中 ccjj 点的颜色。

答案为数组 dpdp 中的最大值。

如果图中有环,则无法遍历完所有点,返回 1-1

时间复杂度 O((n+m)×Σ)O((n + m) \times |\Sigma|),空间复杂度 O(m+n×Σ)O(m + n \times |\Sigma)。其中 Σ|\Sigma| 是字母表大小,这里为 2626,而且 nnmm 分别是节点数和边数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution:
    def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:
        n = len(colors)
        indeg = [0] * n
        g = defaultdict(list)
        for a, b in edges:
            g[a].append(b)
            indeg[b] += 1
        q = deque()
        dp = [[0] * 26 for _ in range(n)]
        for i, v in enumerate(indeg):
            if v == 0:
                q.append(i)
                c = ord(colors[i]) - ord('a')
                dp[i][c] += 1
        cnt = 0
        ans = 1
        while q:
            i = q.popleft()
            cnt += 1
            for j in g[i]:
                indeg[j] -= 1
                if indeg[j] == 0:
                    q.append(j)
                c = ord(colors[j]) - ord('a')
                for k in range(26):
                    dp[j][k] = max(dp[j][k], dp[i][k] + (c == k))
                    ans = max(ans, dp[j][k])
        return -1 if cnt < n else ans
speed

复杂度分析

指标
时间complexity is O(n + m + 26*(n + m)) accounting for topological sort and color count propagation for 26 letters. Space complexity is O(26*n) for the DP table tracking color counts per node.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if you can detect cycles before processing paths to avoid invalid results.

  • question_mark

    Use topological sort to guarantee that color counts propagate correctly without revisiting nodes.

  • question_mark

    Verify the maximum color frequency along each path, not just cumulative edge counts.

warning

常见陷阱

外企场景
  • error

    Failing to detect cycles leading to incorrect color value calculation.

  • error

    Updating color counts incorrectly when multiple predecessors share different color distributions.

  • error

    Assuming only a single color propagates along a path rather than tracking all 26 letters.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute the smallest color value along a path instead of the largest.

  • arrow_right_alt

    Handle graphs where nodes can have multiple colors assigned and count maximum frequency.

  • arrow_right_alt

    Find the number of distinct paths that achieve the largest color value.

help

常见问题

外企场景

有向图中最大颜色值题解:动态·规划 | LeetCode #1857 困难