Skip to content

Commit 07b15cb

Browse files
author
hasibulislam999
committed
Largest Color Value in a Directed Graph problem solved
1 parent d3435fb commit 07b15cb

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* Title: Largest Color Value in a Directed Graph
3+
* Description: There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.
4+
* Author: Hasibul Islam
5+
* Date: 10/04/2023
6+
*/
7+
8+
/**
9+
* @param {string} colors
10+
* @param {number[][]} edges
11+
* @return {number}
12+
*/
13+
const initializeGraph = (n) => {
14+
let G = [];
15+
for (let i = 0; i < n; i++) {
16+
G.push([]);
17+
}
18+
return G;
19+
};
20+
const packDGDegree = (G, Edges, Deg) => {
21+
for (const [u, v] of Edges) {
22+
G[u].push(v);
23+
Deg[v]++;
24+
}
25+
}; // generate direct graph with indegree
26+
27+
const largestPathValue = (colors, edges) => {
28+
let n = colors.length,
29+
m = edges.length,
30+
indegree = Array(n).fill(0);
31+
let g = initializeGraph(n);
32+
packDGDegree(g, edges, indegree);
33+
let order = topologicalSort(g, indegree);
34+
if (order.length == 0) return -1;
35+
let res = 0;
36+
for (let x = 97; x <= 122; x++) {
37+
let c = String.fromCharCode(x),
38+
dp = Array(n).fill(0);
39+
for (let i = 0; i < n; i++) {
40+
let cur = order[i];
41+
if (colors[cur] == c) dp[cur]++;
42+
res = Math.max(res, dp[cur]);
43+
for (const child of g[cur]) dp[child] = Math.max(dp[child], dp[cur]);
44+
}
45+
}
46+
return res;
47+
};
48+
49+
const topologicalSort = (g, indegree) => {
50+
let res = [],
51+
q = [],
52+
n = g.length;
53+
for (let i = 0; i < n; i++) {
54+
// all nodes with no incoming edges
55+
if (indegree[i] == 0) q.push(i);
56+
}
57+
while (q.length) {
58+
let cur = q.shift();
59+
res.push(cur);
60+
for (const child of g[cur]) {
61+
indegree[child]--; // remove an edge from cur to child
62+
if (indegree[child] == 0) q.push(child); // child has no other incoming edges, add to q for next bfs
63+
}
64+
}
65+
for (let i = 0; i < n; i++) {
66+
if (indegree[i] > 0) return [];
67+
}
68+
return res;
69+
};

0 commit comments

Comments
 (0)