Approach
Breadth-first search
For Largest Color Value in a Directed Graph, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 40 lines of Java from the credited upstream file 1857.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int largestPathValue(String colors, int[][] edges) {3 final int n = colors.length();4 int ans = 0;5 int processed = 0;6 List<Integer>[] graph = new List[n];7 int[] inDegrees = new int[n];8 int[][] count = new int[n][26];9 Arrays.setAll(graph, i -> new ArrayList<>());10 11 12 for (int[] edge : edges) {13 final int u = edge[0];14 final int v = edge[1];15 graph[u].add(v);16 ++inDegrees[v];17 }18 19 20 Queue<Integer> q = IntStream.range(0, n)21 .filter(i -> inDegrees[i] == 0)22 .boxed()23 .collect(Collectors.toCollection(ArrayDeque::new));24 25 while (!q.isEmpty()) {26 final int out = q.poll();27 ++processed;28 ans = Math.max(ans, ++count[out][colors.charAt(out) - 'a']);29 for (final int in : graph[out]) {30 for (int i = 0; i < 26; ++i)31 count[in][i] = Math.max(count[in][i], count[out][i]);32 if (--inDegrees[in] == 0)33 q.offer(in);34 }35 }36 37 return processed == n ? ans : -1;38 }39}40