-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
53 lines (48 loc) · 1.39 KB
/
Copy pathsolution.cpp
File metadata and controls
53 lines (48 loc) · 1.39 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int shortCycle(int V, vector<vector<int>> &edges)
{
// build adjacency list
vector<vector<int>> adj(V);
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;
// BFS from each node
for (int s = 0; s < V; ++s)
{
vector<int> dist(V, -1), parent(V, -1);
queue<int> q;
dist[s] = 0;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v : adj[u])
{
if (dist[v] == -1)
{
// unvisited: normal BFS expansion
dist[v] = dist[u] + 1;
parent[v] = u;
q.push(v);
}
else if (parent[u] != v)
{
// visited and not the parent => found a cycle
int cycle_len = dist[u] + dist[v] + 1;
ans = min(ans, cycle_len);
}
}
}
}
return ans == INT_MAX ? -1 : ans;
}
};