Skip to content

Commit 4f373f6

Browse files
authored
Create 2608-shortest-cycle-in-a-graph.js
1 parent dce7388 commit 4f373f6

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

2608-shortest-cycle-in-a-graph.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @return {number}
5+
*/
6+
const findShortestCycle = function(n, edges) {
7+
let res = Infinity
8+
const graph = new Map()
9+
for(const [u, v] of edges) {
10+
if(graph.get(u) == null) graph.set(u, [])
11+
if(graph.get(v) == null) graph.set(v, [])
12+
graph.get(u).push(v)
13+
graph.get(v).push(u)
14+
}
15+
for(let i = 0; i < n; i++) {
16+
bfs(i)
17+
}
18+
19+
if(res === Infinity) return -1
20+
return res
21+
22+
function bfs(src) {
23+
const parent = Array(n), dis = Array(n).fill(Infinity)
24+
let q = []
25+
dis[src] = 0
26+
q.push(src)
27+
while(q.length) {
28+
const node = q.shift()
29+
for(const nxt of (graph.get(node) || [])) {
30+
if(dis[nxt] === Infinity) {
31+
dis[nxt] = dis[node] + 1
32+
parent[nxt] = node
33+
q.push(nxt)
34+
} else if(parent[node] !== nxt && parent[nxt] !== node) {
35+
res = Math.min(res, dis[nxt] + dis[node] + 1)
36+
}
37+
}
38+
}
39+
}
40+
};

0 commit comments

Comments
 (0)