2608. 图中的最短环

题目链接:2608. 图中的最短环

方法:BFS + 技巧

解题思路

  • 环一定包含\(edges\)数组中的某条边;
  • 遍历\(edges\)数组,对于某一条边<\(u, v\)>,以\(v\)为起点进行\(bfs\)搜索,禁止通过边<\(u, v\)>(技巧)。在此种情况下若能搜到\(v\),说明存在环,且当前环的长度为\(当前层数 + 1\),即在禁止通过边<\(u, v\)>的情况下,\(u\) -> \(v\)\(的最短距离 + 1\),因此可以设置一个\(dist\)数组存储最短距离;
  • 然后取所有环的最小值。

代码

class Solution {
public:
    int findShortestCycle(int n, vector<vector<int>>& edges) {
        vector<vector<int>> adj(n);
        for (auto &e : edges) {
            int u = e[0], v = e[1];
            adj[u].push_back(v);
            adj[v].push_back(u);
        }
        int ans = INT_MAX;
        for (auto &e : edges) {
            int st = e[0], ed = e[1];
            vector<int> dist(n), isVist(n);
            queue<int> q;
            q.push(st);
            isVist[st] = 1;
            while (!q.empty()) {
                int u = q.front();
                q.pop();
                for (auto &v : adj[u]) {
                    if ((u == st && v == ed) || isVist[v]) continue;
                    dist[v] = dist[u] + 1;
                    q.push(v);
                    isVist[v] = 1;
                }
            }
            if (dist[ed] != 0) ans = min(ans, dist[ed] + 1);
        }
        return ans == INT_MAX ? -1 : ans;
    }
};

复杂度分析

时间复杂度:\(O(En),E = 边的数量\)
空间复杂度:\(O(n + E),邻接表存储图\)

posted @ 2023-04-09 01:07  lixycc  阅读(36)  评论(0)    收藏  举报