Shortest Cycle in a Graph
Posted onlyblues
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Shortest Cycle in a Graph相关的知识,希望对你有一定的参考价值。
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 \\textedges.length \\leq 1000$
- $\\textedges[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))$:
class Solution public: int findShortestCycle(int n, vector<vector<int>>& edges) vector<vector<int>> g(n); for (auto &p : edges) g[p[0]].push_back(p[1]); g[p[1]].push_back(p[0]); int ret = 0x3f3f3f3f; for (auto &p : edges) vector<int> dist(n, 0x3f3f3f3f); dist[p[0]] = 0; queue<int> q(p[0]); while (!q.empty()) int t = q.front(); q.pop(); for (auto &i : g[t]) if (t == p[0] && i == p[1] || i == p[0] && t == p[1]) continue; if (dist[i] > dist[t] + 1) dist[i] = dist[t] + 1; q.push(i); ret = min(ret, dist[p[1]] + 1); if (ret == 0x3f3f3f3f) ret = -1; return ret; ;
参考资料
最小环 - OI Wiki:https://oi-wiki.org/graph/min-circle/
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17319160.html
c_cpp find_all_cycle_in_graph_dfs
以上是关于Shortest Cycle in a Graph的主要内容,如果未能解决你的问题,请参考以下文章
The Shortest Path in Nya Graph HDU - 4725
HDU 4725 The Shortest Path in Nya Graph(构图)
hdu 4725 The Shortest Path in Nya Graph
HDU - 4725 (The Shortest Path in Nya Graph)层次网络