Skip to content

Commit 23b830f

Browse files
authored
Update 2360-longest-cycle-in-a-graph.js
1 parent 0f19100 commit 23b830f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

2360-longest-cycle-in-a-graph.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,52 @@
1+
/**
2+
* @param {number[]} edges
3+
* @return {number}
4+
*/
5+
const longestCycle = function(edges) {
6+
const n = edges.length;
7+
const visited = new Array(n).fill(false);
8+
const ind = new Array(n).fill(0);
9+
for (let i = 0; i < n; i++) {
10+
if (edges[i] !== -1) {
11+
ind[edges[i]]++;
12+
}
13+
}
14+
let q = []
15+
for(let i = 0; i < n; i++) {
16+
if (ind[i] === 0) {
17+
q.push(i);
18+
}
19+
}
20+
while(q.length) {
21+
const node = q.pop()
22+
visited[node] = true;
23+
const nxt = edges[node];
24+
if(nxt !== -1) {
25+
ind[nxt]--;
26+
if (ind[nxt] === 0) {
27+
q.push(nxt);
28+
}
29+
}
30+
}
31+
let res = -1
32+
for(let i = 0; i < n; i++) {
33+
if (!visited[i]) {
34+
let cnt = 0
35+
let cur = i
36+
while (!visited[cur]) {
37+
visited[cur] = true
38+
cur = edges[cur]
39+
cnt++
40+
}
41+
res = Math.max(res, cnt)
42+
}
43+
}
44+
45+
return res
46+
};
47+
48+
// another
49+
150
/**
251
* @param {number[]} edges
352
* @return {number}

0 commit comments

Comments
 (0)