G-12. Detect a Cycle in an Undirected Graph using DFS | C++ | Java

Поділитися
Вставка
  • Опубліковано 2 гру 2024

КОМЕНТАРІ • 223

  • @takeUforward
    @takeUforward  2 роки тому +83

    Let's continue the habit of commenting “understood” if you got the entire video. Please give it a like too, you don't 😞
    Do follow me on Instagram: striver_79

    • @darveshchhatani1411
      @darveshchhatani1411 2 роки тому

      Please complete the series ASAP

    • @Sumeet_100
      @Sumeet_100 Рік тому

      Hello bhaiya I have doubt that why the time complexity is O(N+2*E) why not O(2*E)

    • @tasneemayham974
      @tasneemayham974 10 місяців тому

      @@Sumeet_100 Because you are going for all nodes N AND(+) visiting all degrees means 2E.

  • @dipaligangawane980
    @dipaligangawane980 2 роки тому +35

    Really very good lecture series. Waiting for the next lectures.

  • @cinime
    @cinime 2 роки тому +13

    Understood! So fantastic explanation as always, thank you very much!!

  • @abhinavtomar8518
    @abhinavtomar8518 Рік тому +7

    Amazing explanation bhaiya really amazing. Was trying to understand it from many source but was not able to understand properly. Really enjoy your teaching. Keep going bhaiya

  • @vikasbagri1225
    @vikasbagri1225 2 роки тому +9

    understood it very well
    Your explanation is awesome

  • @selva-qs9dw
    @selva-qs9dw 5 місяців тому +3

    Without seeing a code i had doned
    Credits goes to striver who has an talent to make it as easy entire dsa for us....❤

  • @harshvardhansingh2272
    @harshvardhansingh2272 2 роки тому +11

    understood striver
    was able to do this by dfs by myself after watching and getting the concept from last video
    Amazing content as always

    • @prakhaxr
      @prakhaxr Рік тому +7

      wah nanhe striver

    • @singhharsh8019
      @singhharsh8019 Рік тому +1

      @@prakhaxr sure, I'll take it as a compliment🙂

  • @anushravishankar9741
    @anushravishankar9741 Рік тому +2

    Understanding more and more each day that I'm not smart enough to understand this high level logic
    Spent 1 year to understand, still haven't understood anything

  • @rachitchaddha999
    @rachitchaddha999 Рік тому +1

    Bhaiya ur teaching style is awesome.

  • @casinarro
    @casinarro Рік тому +2

    It really feels good learning from you

  • @anaghakr9900
    @anaghakr9900 Місяць тому

    Amazing explanation for DFS..

  • @chandramoulipanyam5805
    @chandramoulipanyam5805 2 роки тому

    Classic style of Explanation

  • @vikramragunathan6392
    @vikramragunathan6392 Рік тому

    The way you explained. Just wow 😃😃

  • @mount2020
    @mount2020 Рік тому

    kya hi hai bhai..u make to feel the concept..loving ur content so much

  • @hashcodez757
    @hashcodez757 3 місяці тому

    "UNDERSTOOD BHAIYA!!"

  • @koushikkumar481
    @koushikkumar481 3 місяці тому

    understood Striver Bhaiya ❤❤

  • @vishankpathariya5926
    @vishankpathariya5926 5 місяців тому

    great explanation bhaiya, totally understood

  • @anshusharma11
    @anshusharma11 Рік тому +1

    Thanks for the wonderful explanation.

  • @muskangupta5873
    @muskangupta5873 7 місяців тому

    got the intution because of your rotten oranges videos, i felt it is almost similar to that, thanks understood

  • @AgrimArtofficial
    @AgrimArtofficial 7 місяців тому

    This question can also be done by using the concept V=E+1 in cyclic undirected graph using dfs

  • @tasneemayham974
    @tasneemayham974 10 місяців тому

    PERFECTTTT STRIVERRR!!!!
    UNDERSTOOODDDD

  • @DivineVision201
    @DivineVision201 2 роки тому +2

    understood bhaiya. Are there more videos coming for Graph in this playlist? It would be very helpful if there are more to come..
    But great work..

  • @VikasBagri-i5j
    @VikasBagri-i5j 4 місяці тому

    understood, thanks for this amazing series

  • @KUMARSAURABH-s5i
    @KUMARSAURABH-s5i 6 місяців тому

    Amazing session Understood!!

  • @DevashishJose
    @DevashishJose 10 місяців тому

    Understood, Thank you so much

  • @sripriyapotnuru5839
    @sripriyapotnuru5839 2 роки тому

    Thank you, Striver 🙂

  • @rishabhgupta9846
    @rishabhgupta9846 2 роки тому +1

    understood,great explanation

  • @Joy-b6r
    @Joy-b6r 6 місяців тому +1

    Isn't the both conditions are same inside the loop why we need if condition inside if pls explain...,

  • @govindsharma7696
    @govindsharma7696 2 роки тому

    Understood bhaiya 👍

  • @fairoossahfeerulwasihf1139
    @fairoossahfeerulwasihf1139 3 місяці тому

    will it work fine even for this case where 2 nodes are there each points each other ond forming cycle?

  • @abhichi
    @abhichi 2 роки тому

    Understood!!More!!✌🏻

  • @roshansah691
    @roshansah691 2 роки тому

    Nice explanation, i understood 👍

  • @jagratgupta8392
    @jagratgupta8392 Рік тому +1

    understood sir very nice

  • @RVcalisthenics
    @RVcalisthenics 2 місяці тому

    understood striver

  • @supriyamanna715
    @supriyamanna715 2 роки тому +1

    understood! Thanks man

  • @sanketmudholkar2889
    @sanketmudholkar2889 2 роки тому

    Bold me "UNDERSTOOD"

  • @UECAshutoshKumar
    @UECAshutoshKumar Рік тому +1

    Thank you sir

  • @codeman3828
    @codeman3828 7 місяців тому

    Thanks for the series

  • @fadebeyond
    @fadebeyond 2 роки тому

    Understood Bhaiya.

  • @harshwardhanpatki846
    @harshwardhanpatki846 Рік тому

    Understood sir 🙇‍♂️

  • @codewithom11
    @codewithom11 Рік тому

    Thank You So Much Sir😇

  • @Simran_048
    @Simran_048 4 місяці тому +1

    Simple intution is : It's not the parent still already visited that means cycle exists

  • @utkarshpatidar167
    @utkarshpatidar167 Рік тому

    Understood 🙌🏻

  • @AjayYadav-xi9sj
    @AjayYadav-xi9sj 2 роки тому +1

    When is the possible date of completion of the series.

  • @shubhankarmondal8690
    @shubhankarmondal8690 2 роки тому

    Understood 🙌🔥

  • @abhinavanand1904
    @abhinavanand1904 Рік тому

    Can anyone tell me that why striver has used a vector of array for the visited array instead of a single vector/array in C++ code, or its just mistyped while coding ??

  • @adebisisheriff159
    @adebisisheriff159 10 місяців тому

    Amazing....... Always

  • @nathonluke4058
    @nathonluke4058 2 роки тому

    Loved it and understood

  • @debanjan10
    @debanjan10 Рік тому +1

    understood sir

  • @subhadeepghosh2813
    @subhadeepghosh2813 2 роки тому

    plz make a video on snake and ladder.love u bro

  • @them.pranay7196
    @them.pranay7196 3 місяці тому

    super duper hit video

  • @shivanshsingh176
    @shivanshsingh176 2 роки тому +3

    Instead of "if(dfs(adjacentNode, node, visited, adj) == true)
    return true; ", if we directly return the dfs function, then it is incorrect. Whu so ?
    I think It should be same

    • @devanshchauhan7065
      @devanshchauhan7065 2 роки тому +2

      ya exactly, same doubt, can someone explain please!

    • @gautamsingh2599
      @gautamsingh2599 Рік тому

      in the above statement it the output of the function is true it will directly return it and if you return at last it may or may not return true always

    • @Jaydeeeeeeep
      @Jaydeeeeeeep Рік тому

      Because detect function will return true or false for every component between one to n,
      Lets say first component has no cycle, but second one has a cycle.
      But according to your code, it will not go to second component, it will just return false after iterating in first component.
      So, if detect function sends a true, then only you should return true, else nothing

    • @vijaymehrotra3236
      @vijaymehrotra3236 Рік тому

      in directly returning it will always return something
      but in correct method shone in video it will only return true if the dfs function is true

  • @parshchoradia9909
    @parshchoradia9909 Рік тому

    Understood Sir!

  • @mriduljain6809
    @mriduljain6809 Рік тому

    Understood Bhaiya

  • @atharvadeshmukh6328
    @atharvadeshmukh6328 9 місяців тому

    Understood 😄

  • @vaibhavchauhan1930
    @vaibhavchauhan1930 2 роки тому

    understood, Thank you so much

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 7 місяців тому

    thank you Bhaiya

  • @adityasaxena6971
    @adityasaxena6971 Рік тому

    Understood💯

  • @DeadPoolx1712
    @DeadPoolx1712 2 дні тому

    UNDERSTOOD;

  • @utsavkumar6048
    @utsavkumar6048 Рік тому

    understood sirji

  • @TravelTracksByDebo
    @TravelTracksByDebo 2 роки тому

    understood bhaiya

  • @ANURAGSINGH-nl2ll
    @ANURAGSINGH-nl2ll Рік тому

    understood thank you

  • @aparna5364
    @aparna5364 2 роки тому

    Understood 🎊

  • @fmkhandwala39
    @fmkhandwala39 2 роки тому

    UNDERSTOOD!

  • @tahmidulislamomi1398
    @tahmidulislamomi1398 Рік тому

    Superb

  • @jaishriharivishnu
    @jaishriharivishnu 5 місяців тому

    the concept of more than two parent to detect cycle is also good......
    If in any adjacency list, if we find two or more visited node during BFS or DFS in a undirected graph then it will have a cycle.
    bool detectcycle(int i, vector&vis, vectoradj[]){
    bool iscycledetected=false;
    vis[i]=1;
    int count=0;
    for(auto K:adj[i]){
    if(vis[K])count++;
    }
    if(count>1)iscycledetected=true;// this is the check for cycle

    for(auto K:adj[i]){
    if(!vis[K]){
    bool x1=detectcycle(K,vis,adj);
    iscycledetected=x1|iscycledetected;
    }
    }
    return iscycledetected;
    }

    bool isCycle(int V, vector adj[]) {
    // This is the main function
    vectorvis(V);
    for(int i=0; i

  • @Desi_Debugger
    @Desi_Debugger Рік тому

    bhaiya ji maja agaya

  • @coolgaurav5163
    @coolgaurav5163 3 місяці тому

    Understoood

  • @sumeetubale3923
    @sumeetubale3923 Рік тому +2

    why the time complexity is O(N+ 2*E) instead of that why not O(2*E) ??

    • @gouravchaki7990
      @gouravchaki7990 Рік тому

      Cuz a loop runs from 1->n to check whether node is visited or not, if not visited the dfs is performed.

  • @yashgupta6797
    @yashgupta6797 2 роки тому

    understood sir!

  • @pratapsingh9638
    @pratapsingh9638 Рік тому

    striver please make videos on topic like segment tree

  • @isheep9025
    @isheep9025 Рік тому +2

    Using non recursive DFS:
    class Solution {
    public:
    bool solver(int V,vector & visited,vector adj[],int child,int parent) {

    stack st;
    st.push({child,parent});

    while(!st.empty())
    {
    auto p=st.top();
    int child=p.first;
    int parent=p.second;
    st.pop();
    if(visited[child]==false)
    visited[child]=true;

    for(int ele:adj[child])
    {
    if(!visited[ele])
    {
    st.push({ele,child});
    }

    else if(ele!=parent)
    return true;
    }
    }

    return false;

    }
    public:
    // Function to detect cycle in an undirected graph.
    bool isCycle(int V, vector adj[]) {

    vector visited(V,0);

    for(int i=0;i

  • @ashishbhardwaj4334
    @ashishbhardwaj4334 Рік тому

    UNDERSTOOD

  • @ritikkoshta5792
    @ritikkoshta5792 Рік тому

    understood 😁😁

  • @himanshugupta-mz2yk
    @himanshugupta-mz2yk Рік тому

    Bhaiya Python code in coding ninja is not accepted but code of other languages are accepted

  • @Niki_0011
    @Niki_0011 7 місяців тому

    Understood ++

  • @shreyarawatvlogs6920
    @shreyarawatvlogs6920 11 місяців тому

    I'm not understanding why my code is not working on GFG

  • @cypher7536
    @cypher7536 2 роки тому

    Understood!

  • @aniket6676
    @aniket6676 2 роки тому +4

    Hey Striver,
    I had a doubt, why do we need to store the parent of each node?
    Can't we just count the number of neighboring nodes, of a particular node, that are visited,
    if the count is more than 1, for any node, then we can conclude that the cycle is present?
    Plz let me know if I am missing out on something in my approach.
    Following is the implementation for the above logic:
    bool detectDfs(int start, vector adj[], int vis[]){
    vis[start] = 1;
    int visCnt = 0;
    bool flag = false;
    for(auto it : adj[start]){
    if(++visCnt > 1) flag = true;
    else if(!vis[it]){
    flag = flag || detectDfs(it, adj, vis);
    }
    if(flag == true) return flag;
    }
    return flag;
    }
    bool isCycle(int V, vector adj[]) {
    // Code here
    int vis[V] = {0};
    for(int i = 0; i < V; i++){
    if(!vis[i] && detectDfs(i, adj, vis)) return true;
    }
    return false;
    }

    • @kanishkraj5640
      @kanishkraj5640 2 роки тому

      No..There is possibility when there are more than one visited and the graph will not contain cycle...Refer GFG Article for such example.

    • @sviswesh3555
      @sviswesh3555 2 роки тому

      @@kanishkraj5640 I understood @Aniket 's qn but couldn't understand your answer. How can a node be visited, not be the parent, and yet no cycle is formed?

    • @shripandey4120
      @shripandey4120 Рік тому

      I think, you are right.

    • @illusionhex1200
      @illusionhex1200 Рік тому

      In this example you can visit back to the parent node if not stored them.
      1 ( 2 3)
      2 (1 3)
      Here you will go to 2 from 1 and again 1 from 2 and you got your cycle when there is no cycle at all.

    • @arindammandal1513
      @arindammandal1513 Рік тому

      No, if u have a graph with one node and 3 outwards edge , then it doesnt mean its a cycle right?
      like 1--->2,3,4
      so u visit 2,3 from 1 and visit counts become 2 > 1 , does that mean it has a cycle? No

  • @Anony.musk01
    @Anony.musk01 Рік тому

    one doubt, why do you write functions under private? any specific reason for that?

    • @omkarshendge5438
      @omkarshendge5438 Рік тому +1

      you dont want that function to be exposed somewhere else! you specifically want dfs or dfs for this solution class only and other classes if made can have their methods likewise.
      yes u can add the function under public too not an issue but as far as clean code is concerned its better to add under private
      "Methods that serve as the inner workings of your class and don’t output or display information." read this carefully for private

  • @-Corvo_Attano
    @-Corvo_Attano 2 роки тому +1

    understood :)

  • @kritisingh3194
    @kritisingh3194 2 роки тому

    Understood. :)

  • @kholiyamails1257
    @kholiyamails1257 2 роки тому

    thanks thanks thanks 😅

  • @ayushgarg9099
    @ayushgarg9099 Рік тому

    A simple question if anyone can help me understand!
    If we are given a source node and we are performing DFS on a connected undirected graph(i.e. a single component), how is the time complexity O(N+2E), shoudn't it be just O(2E) which is summation of degrees?

    • @aprajitakumari3745
      @aprajitakumari3745 Рік тому

      For N nodes we are traversing in the wrost case

    • @anshumaan1024
      @anshumaan1024 Рік тому +1

      @@aprajitakumari3745 because for every node, we are traversing all its adjacent nodes

    • @reee896
      @reee896 Рік тому

      So In the worst case the 2E will not be done cause worst case means every will be a component in itself

  • @iDepth
    @iDepth 2 роки тому

    Understood

  • @prajwalhorti3717
    @prajwalhorti3717 2 роки тому

    understood!

  • @gamerglobe4839
    @gamerglobe4839 2 роки тому +1

    can someone please help me to find out why this code is not working..
    class Pair{
    int first,second;
    public Pair(int first,int second){
    this.first=first;
    this.second=second;
    }
    }
    class Solution {
    boolean dfscdetect(int node,int parent,ArrayList adj,int vis[]){
    vis[node]=1;
    for(int nbs:adj.get(node)){
    if(vis[nbs]==0){
    return dfscdetect(nbs,node,adj,vis) || false;
    }
    else{
    if(nbs!=parent)
    return true;
    }
    }
    return false;
    }
    // Function to detect cycle in an undirected graph.
    public boolean isCycle(int V, ArrayList adj) {
    int vis[]=new int[V];
    for(int i=0;i

    • @d1vyanshu
      @d1vyanshu Рік тому

      In the dfsdetect function you should return true only when dfsdetect(...) is true, otherwise it will prematurely return false if it is false.

    • @lakshsinghania
      @lakshsinghania Рік тому

      @@d1vyanshu then why for bfs it was working without writing == true ?
      can u explain

  • @DilpreetSingh-cs7yz
    @DilpreetSingh-cs7yz 2 роки тому +2

    Why writing the fucntion in private ?

  • @sypher4735
    @sypher4735 2 роки тому

    understood.

  • @kushagramishra3026
    @kushagramishra3026 2 роки тому +2

    "Understood"

  • @gururajsavalgi4496
    @gururajsavalgi4496 3 місяці тому

    nice

  • @VEDANSHSHARMA-o6k
    @VEDANSHSHARMA-o6k Місяць тому

    ur awesome

  • @Dadycalling55
    @Dadycalling55 2 роки тому

    understood

  • @Yash-uk8ib
    @Yash-uk8ib 2 роки тому +3

    Sir, a small doubt?
    Lets say the for loop calls dfs fn X times where X

    • @sumerrawat6947
      @sumerrawat6947 2 роки тому +2

      X + O(N+2E) hoga bro , and X

    • @Yash-uk8ib
      @Yash-uk8ib 2 роки тому +1

      @@sumerrawat6947 thanks sir!!
      Pr ek baat or btadijiye
      Aap bol rhe ho ki har component ki complexity addup hui hai
      To sir is hisab se complexity
      O(c1+2e1) + O(c2+2e2) ..... O(x+2ex ) honi chiye thi?
      Agr yhi hai to kya ye eqn hi X + O(N+2E) ke equal hai?

    • @sumerrawat6947
      @sumerrawat6947 2 роки тому +5

      @@Yash-uk8ib dekh bhai
      Lets say we have 4 connected components
      so total 4 calls will be made
      complexity of each component
      for iteration 1:
      O(N1+2E1)
      for iteration 2:
      O(N2+2E2)
      for iteration 3
      O(N3+2E3)
      for iteration 4
      O(N4+2E4)
      as the number of nodes are different in each componenet
      total TIME COMPLEXITY =
      4 + O(N1+N2+N3+N4) + 2(E1+E2+E3+E4)
      = 4+O(N + 2E )
      or
      X + O(N+2E)
      where X is the total number of calls
      N is total number of nodes in WHOLE GRAPH
      E is total edges in WHOLE GRAPH

    • @MdSarfrazcs
      @MdSarfrazcs 2 роки тому

      @@sumerrawat6947 can you suggest a playlist for time complexity of recursion and graph .

  • @anuraggulati2167
    @anuraggulati2167 2 роки тому

    uinderstood bhaiya

  • @SatyamKumar-bw4vi
    @SatyamKumar-bw4vi 2 роки тому +1

    Hare Krishna.! Great Video

  • @AniketSharma-ct5fv
    @AniketSharma-ct5fv Рік тому

    Don't you think all @all that visited array should be sent with reference ! As without reference ! The function check / detect is running for every element / vertex ! As the vis array is a copy in all the dfs calls !

  • @swaraj.nalawade.4634
    @swaraj.nalawade.4634 2 місяці тому

    class Solution {
    private:
    bool dfs(int node, int parent, vector &vis, vector adj[]){
    vis[node] = 1;
    for(auto &it : adj[node]){
    if(!vis[it]){
    if(dfs(it, node, vis, adj) == true) return true;
    }
    else if(it != parent) return true; // cycle
    }
    return false;
    }
    public:
    // Function to detect cycle in an undirected graph.
    bool isCycle(int V, vector adj[]) {
    vector vis(V, 0);
    for(int i=0; i

  • @brahmkaransingh8804
    @brahmkaransingh8804 2 роки тому

    UnderStood

  • @anonymousboy2868
    @anonymousboy2868 5 місяців тому

    understooddd