Skip to content

Commit 55f3426

Browse files
authored
Create 1857. Largest Color Value in a Directed Graph (#805)
2 parents f7bcdd9 + a319f51 commit 55f3426

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
class Solution {
2+
public:
3+
int maxi = -1;
4+
int dp[100001][26];
5+
bool dfs(int node, vector<int> adj[], vector<int>& vis, string& colors) {
6+
vis[node] = 1;
7+
dp[node][colors[node] - 'a']++;
8+
for (auto it : adj[node]) {
9+
if (!vis[it]) {
10+
if (dfs(it, adj, vis, colors))
11+
return true;
12+
}
13+
14+
for (int i = 0; i < 26; i++)
15+
if (colors[node] - 'a' == i)
16+
dp[node][i] = max(dp[node][i], dp[it][i] + 1);
17+
else
18+
dp[node][i] = max(dp[node][i], dp[it][i]);
19+
}
20+
for(int i=0;i<26;i++)maxi=max(maxi,dp[node][i]);
21+
return false;
22+
}
23+
int largestPathValue(string colors, vector<vector<int>>& edges) {
24+
int n = colors.size();
25+
memset(dp, 0, sizeof(dp));
26+
vector<int> adj[n];
27+
queue<int> q, p;
28+
vector<int> indegree(n, 0);
29+
// creating adjacency matrix
30+
for (auto it : edges) {
31+
adj[it[0]].push_back(it[1]);
32+
indegree[it[1]]++;
33+
}
34+
// topological sort using kahn's algo
35+
for (int i = 0; i < n; i++)
36+
if (indegree[i] == 0) {
37+
q.push(i);
38+
p.push(i);
39+
}
40+
vector<int> z;
41+
while (!p.empty()) {
42+
int node = p.front();
43+
p.pop();
44+
z.push_back(node);
45+
for (auto it : adj[node]) {
46+
indegree[it]--;
47+
if (indegree[it] == 0)
48+
p.push(it);
49+
}
50+
}
51+
//if cycle is present return -1
52+
if (z.size() != n)
53+
return -1;
54+
vector<int> vis(n, false), pathvis(n, false);
55+
// making dfs calls only for nodes which have zero indegree
56+
// other nodes will be included automatically in
57+
// the dp table by dfc calls of these nodes
58+
while (!q.empty()) {
59+
int node = q.front();
60+
q.pop();
61+
if (dfs(node, adj, vis, colors))
62+
return -1;
63+
}
64+
return maxi;
65+
}
66+
};

0 commit comments

Comments
 (0)