[LeetCode] Shortest Cycle in a Graph

2608. Shortest Cycle in a Graph

There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1. The edges in the graph are represented by a given 2D integer array edges, where edges[i] = [ui, vi] denotes an edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.

Return the length of the shortest cycle in the graph. If no cycle exists, return -1.

A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
vector<int> adj[1010];
int dep[1010], par[1010];
long long bfs(int u) {
memset(dep, -1, sizeof dep);
memset(par, -1, sizeof par);
dep[u] = 0;
long long res = INT_MAX;
queue<int> q;
q.push(u);
while(q.size()) {
int u = q.front();
q.pop();
for (auto &v: adj[u]) {
if (dep[v] == -1) {
dep[v] = dep[u] + 1;
par[v] = u;
q.push(v);
} else if(par[u] != v and par[v] != u) {
res = min(res, dep[u] + dep[v] + 1ll);
}
}
}
return res;
}
public:
int findShortestCycle(int n, vector<vector<int>>& edges) {
for(int i = 0; i < n; i++) adj[i].clear();
for(auto e : edges) {
int u = e[0], v = e[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
long long res = INT_MAX;
for(int i = 0; i < n; i++) {
if(adj[i].size() == 1) continue;
res = min(res, bfs(i));
}
return res == INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/02/PS/LeetCode/shortest-cycle-in-a-graph/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.