LeetCode每日一题(1857. Largest Color Value in a Directed Graph)

给定一个由n个彩色节点和m条边的有向图,每个节点从0到n-1编号。任务是找到任何有效路径的最大颜色值,颜色值是该路径上出现最频繁的颜色的节点数量。如果图中存在循环,则返回-1。提供的代码实现了一个解决方案,通过计算节点的入度、颜色计数和使用队列进行广度优先搜索来找出最大颜色值路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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] = [aj, bj] indicates that there is a directed edge from node aj to node bj.

A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> … -> xk such that there is a directed edge from xi to xi+1 for every 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” (red in the above image).

Example 2:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RI8Gsdor-1681017337782)(null)]

Input: colors = “a”, edges = [[0,0]]
Output: -1

Explanation: There is a cycle from 0 to 0.

Constraints:

  • n == colors.length
  • m == edges.length
  • 1 <= n <= 10^5
  • 0 <= m <= 10^5
  • colors consists of lowercase English letters.
  • 0 <= aj, bj < n

提示基本把解这题的关键点都说清楚了, 按提示中的方式来写即可



impl Solution {
    pub fn largest_path_value(colors: String, edges: Vec<Vec<i32>>) -> i32 {
        let colors: Vec<char> = colors.chars().collect();
        let mut counts = vec![vec![0; 26]; colors.len()];
        let mut indegrees = vec![0; colors.len()];
        let edges = edges.into_iter().fold(vec![Vec::new(); colors.len()], |mut l, e| {
            indegrees[e[1] as usize] += 1;
            counts[e[0] as usize][colors[e[0] as usize] as usize - 97] = 1;
            counts[e[1] as usize][colors[e[1] as usize] as usize - 97] = 1;
            l[e[0] as usize].push(e[1] as usize);
            l
        });
        let mut queue: Vec<usize> = indegrees.iter().enumerate().filter_map(|(i, &v)| if v == 0 { Some(i as usize) } else { None }).collect();
        let mut ans = 1;
        let mut visited = 0;
        while let Some(n) = queue.pop() {
            visited += 1;
            ans = ans.max(counts[n].iter().map(|v| *v).max().unwrap());
            for &next in &edges[n] {
                for c in 'a'..='z' {
                    counts[next][c as usize - 97] = counts[next][c as usize - 97].max(counts[n][c as usize - 97] + if colors[next] == c { 1 } else { 0 });
                }
                indegrees[next] -= 1;
                if indegrees[next] == 0 {
                    queue.push(next);
                }
            }
        }
        if visited < colors.len() {
            -1
        } else {
            ans
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值