LeetCode - 1857. Largest Color Value in a Directed Graph
Hard
題目
There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.
You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [
A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.
Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.
Example 1
Input: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]
Output: 3
Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a".
Example 2
Input: colors = "a", edges = [[0,0]]
Output: -1
Explanation: There is a cycle from 0 to 0.
Constraints
n == colors.lengthm == edges.length1 <= n <=0 <= m <=colorsconsists of lowercase English letters.0 <=, < n
解題思路
這題是 有向圖 + DP,並且需要先確認圖中 不能有環
使用 Topological Sort(Kahn’s Algorithm)
- 若最後無法走訪所有節點,代表圖中有環,直接回傳
-1
- 若最後無法走訪所有節點,代表圖中有環,直接回傳
DP 定義:
dp[u][c]:走到節點u時,顏色c出現的最大次數- 共有
26種顏色
建圖與入度:
graph[u]:u能走到哪些節點indeg[v]:有幾條邊指向v
初始化:
- 所有
indeg == 0的節點都可以當起點,放入 queue
- 所有
Topological Sort 過程:
- 每處理一個節點
u- 將
u自己的顏色次數加一dp[u][colors[u] - 'a']++ - 更新答案
- 將
- 對於每一條邊
u -> v- 所有能走到
u的最佳路徑,都可以延伸到v - 對所有顏色:
dp[v][c] = max(dp[v][c], dp[u][c])
- 更新
indeg[v] - 若
indeg[v] == 0,放入 queue
- 所有能走到
- 每處理一個節點
若最後走訪的節點數量不等於
n- 代表存在 cycle,回傳
-1
- 代表存在 cycle,回傳
Solution Code
Time Complexity
O(n + m) × 26
Space Complexity
O(n × 26)
1 | |