Shortest Cycle in a Graph

发布时间 2023-04-14 18:00:44作者: onlyblues

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.

Example 1:

Input: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]
Output: 3
Explanation: The cycle with the smallest length is : 0 -> 1 -> 2 -> 0 

Example 2:

Input: n = 4, edges = [[0,1],[0,2]]
Output: -1
Explanation: There are no cycles in this graph.

Constraints:

  • $2 \leq n \leq 1000$
  • $1 \leq \text{edges.length} \leq 1000$
  • $\text{edges}[i]\text{.length} \ \mathrm{==} \ 2$
  • $0 \leq u_i, v_i < n$
  • $u_i \ne v_i$
  • There are no repeated edges.

 

解题思路

  求最小环的模板题,当时比赛的时候没了解过就没做出来。解决最小环问题可以参考该博客:无向图的最小环问题

  可以发现题目中的$n$最大可以取到$1000$,因此不可以用Floyd的做法。又发现每一条边的权重都为$1$,因此可以枚举每一条边,然后删除这条边,再用bfs来求这条边两个端点间的最短路。这样就能得到包含这条边的环的最小长度。

  AC代码如下,时间复杂度为$O(m(n+m))$:

 1 class Solution {
 2 public:
 3     int findShortestCycle(int n, vector<vector<int>>& edges) {
 4         vector<vector<int>> g(n);
 5         for (auto &p : edges) {
 6             g[p[0]].push_back(p[1]);
 7             g[p[1]].push_back(p[0]);
 8         }
 9         int ret = 0x3f3f3f3f;
10         for (auto &p : edges) {
11             vector<int> dist(n, 0x3f3f3f3f);
12             dist[p[0]] = 0;
13             queue<int> q({p[0]});
14             while (!q.empty()) {
15                 int t = q.front();
16                 q.pop();
17                 for (auto &i : g[t]) {
18                     if (t == p[0] && i == p[1] || i == p[0] && t == p[1]) continue;
19                     if (dist[i] > dist[t] + 1) {
20                         dist[i] = dist[t] + 1;
21                         q.push(i);
22                     }
23                 }
24             }
25             ret = min(ret, dist[p[1]] + 1);
26         }
27         if (ret == 0x3f3f3f3f) ret = -1;
28         return ret;
29     }
30 };

 

参考资料

  最小环 - OI Wiki:https://oi-wiki.org/graph/min-circle/