Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- int mini=1e9;
- private:
- void dfs(int node,int parent,int c,vector<int> &vis,vector<int> &pathVis,vector<int> adjList[]){
- vis[node]=c;
- pathVis[node]=1;
- for(auto it: adjList[node]){
- if(!vis[it]){
- dfs(it,node,c+1,vis,pathVis,adjList);
- }
- else if(parent!=it && pathVis[it]==1){
- mini=min(mini,vis[node]-vis[it]+1);
- }
- }
- pathVis[node]=0;
- }
- public:
- int findShortestCycle(int n, vector<vector<int>>& edges) {
- vector<int> vis(n,0);
- vector<int> pathVis(n,0);
- vector<int> adjList[n];
- for(auto it: edges){
- adjList[it[0]].push_back(it[1]);
- adjList[it[1]].push_back(it[0]);
- }
- for(int i=0;i<n;i++){
- if(!vis[i])
- dfs(i,-1,0,vis,pathVis,adjList);
- }
- if(edges[0][0]==n-2 && mini==n-1) mini--;
- if(mini==1e9) return -1;
- return mini;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement