Skip to content

Commit f8094d9

Browse files
authored
Update 1857-largest-color-value-in-a-directed-graph.js
1 parent d26f7e6 commit f8094d9

File tree

1 file changed

+36
-33
lines changed

1 file changed

+36
-33
lines changed

1857-largest-color-value-in-a-directed-graph.js

Lines changed: 36 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,42 @@
33
* @param {number[][]} edges
44
* @return {number}
55
*/
6-
const largestPathValue = function(colors, edges) {
7-
const graph = {}
8-
const n = colors.length, a = 'a'.charCodeAt(0)
9-
const indegree = Array(colors.length).fill(0)
10-
for(let e of edges) {
11-
if(graph[e[0]] == null) graph[e[0]] = []
12-
graph[e[0]].push(e[1])
13-
indegree[e[1]]++
6+
const largestPathValue = function (colors, edges) {
7+
const graph = {}
8+
const n = colors.length,
9+
a = 'a'.charCodeAt(0)
10+
const indegree = Array(colors.length).fill(0)
11+
for (let e of edges) {
12+
if (graph[e[0]] == null) graph[e[0]] = []
13+
graph[e[0]].push(e[1])
14+
indegree[e[1]]++
15+
}
16+
const cnt = Array.from({ length: n }, () => Array(26).fill(0))
17+
const q = []
18+
for (let i = 0; i < n; i++) {
19+
if (indegree[i] === 0) {
20+
q.push(i)
21+
cnt[i][colors.charCodeAt(i) - a] = 1
1422
}
15-
const cnt = Array.from({ length: n }, () => Array(26).fill(0))
16-
const q = []
17-
for(let i = 0; i < n; i++) {
18-
if(indegree[i] === 0) {
19-
q.push(i)
20-
cnt[i][colors.charCodeAt(i) - a] = 1
23+
}
24+
let res = 0,
25+
seen = 0
26+
while (q.length) {
27+
const u = q[0]
28+
q.shift()
29+
let val = Math.max(...cnt[u])
30+
res = Math.max(res, val)
31+
seen++
32+
if (graph[u] == null) continue
33+
for (let v of graph[u]) {
34+
for (let i = 0; i < 26; i++) {
35+
cnt[v][i] = Math.max(
36+
cnt[v][i],
37+
cnt[u][i] + (i === colors.charCodeAt(v) - a)
38+
)
2139
}
40+
if (--indegree[v] === 0) q.push(v)
2241
}
23-
let res = 0, seen = 0
24-
while(q.length) {
25-
const u = q[0]
26-
q.shift()
27-
let val = Math.max(...cnt[u])
28-
res = Math.max(res, val)
29-
seen++
30-
if(graph[u] == null) continue
31-
for(let v of graph[u]) {
32-
for(let i = 0; i < 26; i++) {
33-
cnt[v][i] = Math.max(cnt[v][i], cnt[u][i] + (i === colors.charCodeAt(v) - a))
34-
}
35-
if(--indegree[v] === 0) q.push(v)
36-
}
37-
}
38-
return seen < colors.length ? -1 : res
39-
};
40-
41-
42+
}
43+
return seen < colors.length ? -1 : res
44+
}

0 commit comments

Comments
 (0)