diff --git a/1857. Largest Color Value in a Directed Graph b/1857. Largest Color Value in a Directed Graph new file mode 100644 index 0000000..18e08b2 --- /dev/null +++ b/1857. Largest Color Value in a Directed Graph @@ -0,0 +1,66 @@ +class Solution { +public: + int maxi = -1; + int dp[100001][26]; + bool dfs(int node, vector adj[], vector& vis, string& colors) { + vis[node] = 1; + dp[node][colors[node] - 'a']++; + for (auto it : adj[node]) { + if (!vis[it]) { + if (dfs(it, adj, vis, colors)) + return true; + } + + for (int i = 0; i < 26; i++) + if (colors[node] - 'a' == i) + dp[node][i] = max(dp[node][i], dp[it][i] + 1); + else + dp[node][i] = max(dp[node][i], dp[it][i]); + } + for(int i=0;i<26;i++)maxi=max(maxi,dp[node][i]); + return false; + } + int largestPathValue(string colors, vector>& edges) { + int n = colors.size(); + memset(dp, 0, sizeof(dp)); + vector adj[n]; + queue q, p; + vector indegree(n, 0); + // creating adjacency matrix + for (auto it : edges) { + adj[it[0]].push_back(it[1]); + indegree[it[1]]++; + } + // topological sort using kahn's algo + for (int i = 0; i < n; i++) + if (indegree[i] == 0) { + q.push(i); + p.push(i); + } + vector z; + while (!p.empty()) { + int node = p.front(); + p.pop(); + z.push_back(node); + for (auto it : adj[node]) { + indegree[it]--; + if (indegree[it] == 0) + p.push(it); + } + } + //if cycle is present return -1 + if (z.size() != n) + return -1; + vector vis(n, false), pathvis(n, false); + // making dfs calls only for nodes which have zero indegree + // other nodes will be included automatically in + // the dp table by dfc calls of these nodes + while (!q.empty()) { + int node = q.front(); + q.pop(); + if (dfs(node, adj, vis, colors)) + return -1; + } + return maxi; + } +};