G-20. Find Eventual Safe States - DFS

Поділитися
Вставка
  • Опубліковано 6 лип 2024
  • GfG-Problem Link: bit.ly/3C90n59
    C++/Java/Codes and Notes Link: takeuforward.org/data-structu...
    DP Series: • Striver's Dynamic Prog...
    SDE Sheet: takeuforward.org/interviews/s...
    Check out our Website for curated resources:
    Our Second Channel: / @striver_79
    In case you are thinking to buy courses, please check below:
    Code "takeuforward" for 15% off at GFG: practice.geeksforgeeks.org/co...
    Code "takeuforward" for 20% off on sys-design: get.interviewready.io?_aff=takeuforward
    Crypto, I use the Wazirx app: wazirx.com/invite/xexnpc4u
    Take 750 rs free Amazon Stock from me: indmoney.onelink.me/RmHC/idje...
    Earn 100 rs by making a Grow Account for investing: app.groww.in/v3cO/8hu879t0
    Linkedin/Instagram/Telegram: linktr.ee/takeUforward
    ---------------------------------------------------------------------------------------------------------------------------

КОМЕНТАРІ • 262

  • @takeUforward
    @takeUforward  Рік тому +77

    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

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

      Your dfs cycle explanation is good enough. That one video does the charm of other questions.

  • @manthenanagendra1077
    @manthenanagendra1077 Рік тому +75

    this man will be remembered for so long for his work

  • @kritisingh3194
    @kritisingh3194 Рік тому +133

    We can eliminate the check array and just use if(pathVis[i] == 0) to get the safe nodes and use the absolute same code as cycle detection in directed graph, just add this in end:
    List res = new ArrayList();
    for(int i=0; i

    • @takeUforward
      @takeUforward  Рік тому +84

      Makes sense! The check array was added to increase the understanding :) Good to see such comments 💯

    • @kritisingh3194
      @kritisingh3194 Рік тому +24

      @@takeUforward Thanks for the quality content! :D

    • @rishavsaha5254
      @rishavsaha5254 Рік тому +17

      Then this question will boil down to checking only the "false" pathVis nodes. Nice!

    • @eshaanpandey7353
      @eshaanpandey7353 Рік тому +3

      @@rishavsaha5254 Exactly

    • @-Corvo_Attano
      @-Corvo_Attano Рік тому +7

      *JAVA CODE USING SINGLE VIS[] ARRAY*
      class Solution {
      private static boolean dfs(int num , int vis[] , List adj){
      vis[num] = 1;
      for(int it : adj.get(num)){
      if(vis[it] == 0){
      if(dfs(it,vis,adj)) return true;
      }else if(vis[it] == 1) return true;
      }
      vis[num] = 2;
      return false;
      }
      List eventualSafeNodes(int v, List adj){
      int vis[] = new int[v];
      for(int i=0;i

  • @pooja_SS
    @pooja_SS Рік тому +129

    Can we just call this channel The Free University?

    • @sumerrawat6947
      @sumerrawat6947 Рік тому +27

      Sad that we have to pay huge sums in our shitty universities despite knowing that it is a waste of money and time

    • @aeroabrar_31
      @aeroabrar_31 Рік тому +6

      and the logo suits too..
      TUF (Take U Forward) ~TFU (The Free University)
      A petition for striver to change the name of the channel..😅😂

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

      Yess bro definitely 😻

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

      Nope you girls exaggerated everything 😢you Lil kid

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

      No

  • @nehathakur40
    @nehathakur40 Рік тому +15

    Some people make excuses and some make it happen, you are perfect example of working hard even if you achieve hell lot in life .Thank you for inspiring me always and motivating me to push my limits. I really respect the efforts you have put ,in making this video inspite of being unwell.

  • @rajsekhardutta8891
    @rajsekhardutta8891 Рік тому +3

    Understood! Great explanation as always. 🤩❤‍🔥

  • @026harshagarwal9
    @026harshagarwal9 Рік тому +1

    This is indeed the best example to explain this question

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

    Super happy as I was able to solve this myself. I have always been scared of graphs but now it seems to be making sense. Thanks a lot

  • @learnwithayush7838
    @learnwithayush7838 Рік тому +5

    Nice video sir you are the reason for thousands of smile everyday when we see Accepted in leetcode

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

    Got a better understanding of the DFS from this.

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

    understood,solving new problems from the solutions you know is main task

  • @KunalSinghStatus
    @KunalSinghStatus Рік тому +4

    bhaiya audio quality is too good ... wonderful explanation. Thank You ❤❤

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

    Understood!! Very well explained!!!

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

    Thanks for the quality content!!

  • @ravi9618
    @ravi9618 Рік тому +8

    this is a great approach, although we can reduce use of check array cause we can calculate pathVis[i] == 0 and add them to safeNodes and return them answer will be same

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

    Understood!! Great explanation

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

    Hey Striver. Great video as always. We appreciate you for making such amazing videos but you need to take care of yourself. We dont want our superstar to fall sick overexerting himself.

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

    Thank you very much. You are a genius.

  • @MMNayem-dq4kd
    @MMNayem-dq4kd 11 місяців тому

    Understood,very well explained.💕💕

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

    Understood very well explained

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

    that whole explanation of all the dfs calls was v.helpfull and good

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

      code likhe ka tareeka bhi bahut mast tha bhaiyaa 🥰🫶

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

    Thank you, Striver 🙂

  • @shashanksingh4708
    @shashanksingh4708 10 місяців тому +2

    i reversed the edges and used topo sort , then added each node as it was being processed in the queue

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

    Great explaination

  • @tasneemayham974
    @tasneemayham974 4 місяці тому

    BESTTTT TEACHHHEERRR EVERRR!!!! THANKKK YOUUU STRIVERR!!

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

    Thank you for your immense efforts Striver. Here is a solution using single array :
    visited=[0]*(n)
    DFS function Call on unvisited nodes :
    DFS(node):
    visited[node]=2 #(1+1) 1 for visited and another 1 to denote path
    for neighbours in graph[node]:
    if visited[neighbours]==0:
    if(recurDFS(neighbours)):return True
    elif visited[neighbours]==2:
    return True
    visited[node]=1 //backTracking the visited path
    Finally whichever nodes are visited only once(1) will be safe nodes and the nodes with 2 are unsafe.
    safeNodes=[]
    for nodes in range(n):
    if visited[nodes]==1:
    safeNodes.append(nodes)
    return safeNodes

  • @stith_pragya
    @stith_pragya 7 місяців тому +1

    Thank You So Much for this wonderful video................🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @modiji8706
    @modiji8706 8 місяців тому +2

    the whole series like a cake walk

    • @NAMAN-wj7dj
      @NAMAN-wj7dj 2 місяці тому +2

      are Modi ji abki baar 400 paar !!

  • @dank7044
    @dank7044 23 дні тому

    Did this on my own,all thanks to your last video ka explanation

  • @preetisahani5054
    @preetisahani5054 8 місяців тому

    Awesome explanation

  • @divyanshpandey3460
    @divyanshpandey3460 Рік тому +5

    another approach to this problem is to call make a dfs function with return type bool. Inside the function we would create a variable bool b initially assigned to true. This dfs function when called for a starting node would return whether that node is safe or not. This function is implemented using recursion and dfs.
    Two vectors isSafe and visited are used. Below is the implementation
    bool dfs(int start,vector &visited,vector adj[],vector &isSafe){
    visited[start]=1;
    bool b=true;
    for(auto node : adj[start]){
    if(!visited[node]){
    b=b && (dfs(node,visited,adj,isSafe));
    }
    else{
    b=b && isSafe[node];
    }
    }
    if(b){

    isSafe[start]=true;
    return true;
    }
    return false;
    }
    vector eventualSafeNodes(int n, vector adj[]) {
    // code here
    vector v;
    vector visited(n,0);
    vector isSafe(n,false);
    for(int i=0;i

  • @s.s.lingeshkumar865
    @s.s.lingeshkumar865 Рік тому +1

    understood a lot anna❤

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

    understood!!!
    Thankyou sir !!!

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

    Hey which tool do you use in your iPad for explanation?

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

    can it be done by this approach?->in cycle detection algorithm using dfs,whenever we are returning true in dfs function(means a cycle is detected)store that node in a data structure and in the end all the nodes which were either a part of cycle or connected to cycle will get stored in that structure,all the remaining nodes which are not there in that data structure will be safe nodes.

  • @saisriangajala8399
    @saisriangajala8399 Рік тому +5

    In undirected graph only components with single node will be safe nodes..

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

    What an explanation!!

  • @Ankit.yt_885
    @Ankit.yt_885 Рік тому

    Very good! Thanks :)

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

    I should say this.I have seen numerous videos of yours Tries, Binary trees,Dp and now I have come here to see this.This lecture by far has given me the most amazing concept .My original intuition was towards topological sort, but I never thought about cycle detection usage here.

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

    Thanks ...tum accha kaam karta hai habibi

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

    Understood sir thankyou and take care sir❤🙇‍♂🙏

  • @atheisttttt
    @atheisttttt Рік тому +6

    Saw recent racism incident in Warsaw (Polland) against Indians - take care bro !

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

    can anyone suggest any other intuition for solving this question apart from cycle method??

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

    Aye aye captain ! 💪🏻

  • @ravisingh-el8np
    @ravisingh-el8np 10 місяців тому

    thanks striver i could code it myself

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

    understood! ❤❤❤❤❤❤❤❤

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

    Hey striver,
    If we consider a graph like 0->1->2 then it is giving 0,1,2 as safe nodes
    But if we look at path from 0 to 1, it doesn't end in a terminal node since 1 is not an terminal node. So my doubt is why 0 is considered as safe node??

  • @UECAshutoshKumar
    @UECAshutoshKumar 10 місяців тому +1

    Thank you sir

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

    understood!!!!

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

    Understood! Super cool explanation as always, thank you very much!!

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

    Seeing the eyes of Stiver itz clear, that he might have recorded the video really late at ni8...thanks for the continuous effort bhaiya, Your content really helps

  • @shivendrasingh8520
    @shivendrasingh8520 21 день тому

    We can use cycle detection technique and return those edges whose pathvisted is not 1 means excluse cycled edges

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

    Understood, maja aagaya

  • @anooshkaa
    @anooshkaa 6 місяців тому

    i have a question. pathvisited just takes care the fact whether the function call has finished or not. so shouldn't do pathvisited[node]=0 before we return anything for that function?

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

    Full Understood 😃

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

    Understood Sir!

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

    Understood 💯💯

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

    Thanks for the video. xor of vis and pathVis seem to give the correct answer. no need check array.

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

    Understood 🙌

  • @pratik.784
    @pratik.784 Рік тому

    Best channel

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

    almost halfway done !

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

    Bhaiya aap mast padhate ho ❤

  • @AditiAgarwal-rw3lq
    @AditiAgarwal-rw3lq Рік тому

    great video

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

    leetcode link: leetcode.com/problems/find-eventual-safe-states/

  • @sarthaksharma9322
    @sarthaksharma9322 21 день тому

    As always an amazing video Striver, just a small question though, instead of keeping a safeNodes and check array, if we are done with the for loop, can't we just directly push the node into the safeNodes array at that point only, I guess if we do this, then we won't require another for loop whose only job is to then read from the check array and push into the safeNodes array.

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

    In the main function, in the for loop, we have used the dfsCheck function, which is supposed to return a boolean value. But here it is not stored anywhere and thus will throw an error.

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

    understood!

  • @sumitworld918
    @sumitworld918 4 місяці тому

    Understood ❤

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

    quality content 😍

  • @user-tk2vg5jt3l
    @user-tk2vg5jt3l 2 місяці тому

    Thank you bhaiya

  • @-VLaharika
    @-VLaharika Рік тому

    Understood 👍

  • @himalayadebbarma-we4pt
    @himalayadebbarma-we4pt 29 днів тому +1

    Understood!!

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

    Understood 😀

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

    Happy teachers day bhaiyya 🙏

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

    Can some please tell me which Cycle detection video he's referring to @ 16:24 . Because the Cycle detection video in this series in for undirected graph.

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

    UNDERSTOOD.

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

    Understood bhaiya

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

    amazing explanation

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

    understood sirji

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

    Understood❤

  • @dojoPojo
    @dojoPojo Рік тому +3

    We can just add safenodes in dfs after visiting all neighbours of it and not ending in cycle so no need to do traversal again
    c++ code :
    class Solution {
    public:
    /*
    find all the nodes that are not part of the cycle
    directed
    so path vis and vis
    */
    bool hascycle(int src, vector& graph, vector&vis, vector&pathvis, vector&safenodes) {
    vis[src]=true;
    pathvis[src]=true;
    for(auto it:graph[src]) {
    if(!vis[it]) {
    if(hascycle(it,graph,vis,pathvis,safenodes))
    return true;
    }
    if(pathvis[it]) {
    return true;
    }
    }
    pathvis[src]=false;
    safenodes.push_back(src);
    return false;
    }
    vector eventualSafeNodes(vector& graph) {

    int n = graph.size();
    vectorvis(n,false);
    vectorpathvis(n,false);
    vectorsafenodes;
    for(int i=0; i

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

    understood bhaiya

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

    “understood”😀

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

    understood

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

    Understood

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

    please create series on string problems

  • @atharvadeshmukh6328
    @atharvadeshmukh6328 4 місяці тому

    Understood!

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

    Understood 😇

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

    understood!!!!!!!!!

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

    Understood Bhaiya

  • @aniruddhadas1778
    @aniruddhadas1778 Рік тому +10

    Instead of using another check array we could easily find the safe states using pathvis only.
    if(pathvis[i]==0)
    {
    ans.add(i);
    }

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

    Understood.

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

    understood✌🤟

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

    understood.

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

    but we can solve this without cycle detection as well, by assuming that each node is a component.

  • @heichou7334
    @heichou7334 10 місяців тому +1

    Really helpful but would love if you explain the code little bit.

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

    UNDERSTOOD

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

    understood💙💚💙

  • @jha.brajesh
    @jha.brajesh 2 місяці тому

    is it not possible? we just find out node in the in the adjacency list which has an empty list, which means that is the safe node. and then find out which all nodes' list contains only that safe node so that those nodes will also be safe nodes.

  • @242deepak
    @242deepak Рік тому +4

    I think you haven't covered cycle detection in directed graph in any of your previous videos in this series.

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

      exactly

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

      @@antassachan1782 It's the 56th video of the playlist go and check it once.

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

      It's the 56th video of the playlist go and check it once.