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:
- There are no repeated edges.
解题思路
求最小环的模板题,当时比赛的时候没了解过就没做出来。解决最小环问题可以参考该博客:无向图的最小环问题。
可以发现题目中的最大可以取到,因此不可以用Floyd的做法。又发现每一条边的权重都为,因此可以枚举每一条边,然后删除这条边,再用bfs来求这条边两个端点间的最短路。这样就能得到包含这条边的环的最小长度。
AC代码如下,时间复杂度为:
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/
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17319160.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2021-04-14 六度空间