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
- 41 lines of C++ from the credited upstream file 1857.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 5 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:3 int largestPathValue(string colors, vector<vector<int>>& edges) {4 const int n = colors.length();5 int ans = 0;6 int processed = 0;7 vector<vector<int>> graph(n);8 vector<int> inDegrees(n);9 queue<int> q;10 vector<vector<int>> count(n, vector<int>(26));11 12 13 for (const vector<int>& edge : edges) {14 const int u = edge[0];15 const int v = edge[1];16 graph[u].push_back(v);17 ++inDegrees[v];18 }19 20 21 for (int i = 0; i < n; ++i)22 if (inDegrees[i] == 0)23 q.push(i);24 25 while (!q.empty()) {26 const int out = q.front();27 q.pop();28 ++processed;29 ans = max(ans, ++count[out][colors[out] - 'a']);30 for (const int in : graph[out]) {31 for (int i = 0; i < 26; ++i)32 count[in][i] = max(count[in][i], count[out][i]);33 if (--inDegrees[in] == 0)34 q.push(in);35 }36 }37 38 return processed == n ? ans : -1;39 }40};41