File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ use std:: collections:: VecDeque ;
2+
3+ impl Solution {
4+ pub fn largest_path_value ( colors : String , edges : Vec < Vec < i32 > > ) -> i32 {
5+ let n = colors. len ( ) ;
6+ let mut graph = vec ! [ vec![ ] ; n] ;
7+ let mut indegree = vec ! [ 0 ; n] ;
8+
9+ for edge in edges {
10+ let u = edge[ 0 ] as usize ;
11+ let v = edge[ 1 ] as usize ;
12+ graph[ u] . push ( v) ;
13+ indegree[ v] += 1 ;
14+ }
15+
16+ let mut queue = VecDeque :: new ( ) ;
17+ for i in 0 ..n {
18+ if indegree[ i] == 0 {
19+ queue. push_back ( i) ;
20+ }
21+ }
22+
23+ let mut color_count = vec ! [ vec![ 0 ; 26 ] ; n] ;
24+ let mut visited = 0 ;
25+ let colors = colors. as_bytes ( ) ;
26+ let mut max_color_value = 0 ;
27+
28+ while let Some ( node) = queue. pop_front ( ) {
29+ visited += 1 ;
30+ let color_index = ( colors[ node] - b'a' ) as usize ;
31+ color_count[ node] [ color_index] += 1 ;
32+ max_color_value = max_color_value. max ( color_count[ node] [ color_index] ) ;
33+
34+ for & neigh in & graph[ node] {
35+ for i in 0 ..26 {
36+ color_count[ neigh] [ i] = color_count[ neigh] [ i] . max ( color_count[ node] [ i] ) ;
37+ }
38+ indegree[ neigh] -= 1 ;
39+ if indegree[ neigh] == 0 {
40+ queue. push_back ( neigh) ;
41+ }
42+ }
43+ }
44+
45+ if visited != n as i32 {
46+ return -1 ;
47+ }
48+
49+ max_color_value
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments