-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path18-Shortest Cycle in Undirected Graph.cpp
More file actions
55 lines (45 loc) · 1.23 KB
/
18-Shortest Cycle in Undirected Graph.cpp
File metadata and controls
55 lines (45 loc) · 1.23 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
54
55
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> gr;
int shortest_cycle(int n)
{
// To store length of the shortest cycle
int ans = INT_MAX;
// For all vertices
for (int i = 1; i <= n; i++) {
vector<int> dist(n+1, (int)(1e9));
vector<int> par(n+1, -1);
dist[i] = 0;
queue<int> q;
q.push(i);
while (!q.empty()) {
int x = q.front();
q.pop();
for (int child : gr[x]) {
if (dist[child] == (int)(1e9)) {
dist[child] = 1 + dist[x];
par[child] = x;
q.push(child);
}
else if (par[x] != child and par[child] != x){
ans = min(ans, dist[x] + dist[child] + 1);
}
}
}
}
if (ans == INT_MAX){
return -1;
}
else{
return ans;
}
}
int solve(int n,vector<vector<int>> edges){
gr=vector<vector<int>>(n+1,vector<int>());
for(int i=0;i<edges.size();i++){
int x=edges[i][0],y=edges[i][1];
gr[x].push_back(y);
gr[y].push_back(x);
}
return shortest_cycle(n);
}