G-19. Detect cycle in a directed graph using DFS | Java | C++

Поділитися
Вставка
  • Опубліковано 20 січ 2025

КОМЕНТАРІ • 378

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

    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

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

      when i used pathVis array instead of vis arr in "traverse for adjacent nodes" section {Line -15} . I am getting TLE, could anyone explain me why?

    • @praveen._.m._.
      @praveen._.m._. Рік тому

      @@adityasinghjadon5760 path[I] came back to zero when cycle not in that path,so the node never consider as visited ,time limit exceed

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

      yes

  • @mrbug100yearsago5
    @mrbug100yearsago5 2 роки тому +50

    I cant do anything to support u....
    So , showing my love and support by commenting...
    Hats off to all ur efforts and thanq for everything ,you are doing for the community ❣

    • @coder_07
      @coder_07 4 місяці тому +2

      did you took TUF+ subscription ? like u wrote "can anything for striver"

  • @beinghappy9223
    @beinghappy9223 2 роки тому +164

    The concept of visited and path visited is really amazing

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

      Facts. This concept seems to stick with me the most

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

      Visited pathVisited rocks

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

    understood !!!
    only youtuber who made coding easy for us.
    Rest others are busy in making cringe video of 3 lpa to 1 cr lpa types video.

  • @unknown2003august
    @unknown2003august 6 місяців тому +9

    It is now became a habit of just watch explanation and code by yourself. 😊😊
    Thank you Striver ,Never thought that i can be able to solve graph problem by my own in just one go

  • @RishabhSharma-p9o
    @RishabhSharma-p9o 5 місяців тому +13

    private boolean DFS(int i,int[] vis,ArrayList adj){
    vis[i]=1;
    for(int it:adj.get(i)){
    if(vis[it]==0){
    if(DFS(it,vis,adj)){
    return true;
    }
    }
    else if(vis[it]==1){
    return true;
    }
    }
    vis[i]=2;
    return false;
    }
    without the pathVis approach.
    Great leacture.

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

      Can you please tell why we always declare the other function as private?

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

      @@saimasyeda6544 Doesn't Matter here, Its just one of OOPS Concept

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

      @@aniketainapur3315 OK thanks

  • @harshith4549
    @harshith4549 7 місяців тому +5

    Understood well and doing dry run on my own got the algo into my head. Truly amazing brother💯.

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

    Best explanation and logic abstraction ever!!! Thanks a lot

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

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

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

    Using single array was new to me .... Thanks a lot man 🙏🏻❤

  • @vishalsujaykumar5245
    @vishalsujaykumar5245 2 роки тому +74

    Using single visited array :
    /*Complete the function below*/
    class Solution {
    // Function to detect cycle in a directed graph.
    public static boolean dfs(int src, int[] visited, ArrayList adj)
    {
    //Mark the node as visited
    visited[src] = 2;

    for(int nbr : adj.get(src))
    {
    //If unvisited
    if(visited[nbr] == 0)
    {
    //Mark it as same path
    visited[nbr] = 2;
    if(dfs(nbr,visited,adj) == true)
    {
    return true;
    }
    }
    else if(visited[nbr] == 2)
    {
    return true;
    }
    }

    //Backtrack to visited
    visited[src] = 1;
    return false;

    }
    public boolean isCyclic(int V, ArrayList adj) {
    // code here

    //Space optimization using only visited array

    int[] visited = new int[V];
    Arrays.fill(visited, 0);


    /*
    0 - Unvisited
    1 - Visited
    2 - Same Path
    */


    for(int i = 0 ; i < V ; i++)
    {
    if(visited[i] == 0)
    {
    if(dfs(i,visited,adj) == true)
    {
    return true;
    }
    }
    }
    return false;

    }
    }

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

      visited[nbr] = 2; this statement in line number 12 is not necessary right, because however in dfs call you will be marking it as 2

    • @techy_ms-e2m
      @techy_ms-e2m 9 місяців тому

      @@santoshb7776 Yes

    • @imPriyansh77
      @imPriyansh77 8 місяців тому +1

      @@santoshb7776 Yeah

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

      public boolean dfsTechnique2(int V, ArrayList adj) {
      // code here
      int[] vis = new int[V];
      for (int i = 0; i < V; i++) {
      if (vis[i] == 0) {
      if (dfs2(i, adj, vis)) {
      return true;
      }
      }
      }
      return false;
      }
      public boolean dfs2(int node, ArrayList adj, int[] vis) {
      vis[node] = 2;
      ArrayList neigh = adj.get(node);
      for (int i : neigh) {
      if (vis[i] == 0) {
      if (dfs2(i, adj, vis)) {
      return true;
      }
      }
      else {
      if (vis[i] == 2) {
      return true;
      }
      }
      }
      vis[node] = 1;
      return false;
      }
      This is my space otpimized code, giving me TLE in case 201.

  • @Dipanshutripathi2407
    @Dipanshutripathi2407 9 днів тому

    Shuru majboori mai kiya tha pr ab maja aane laga hai🙂🙃😊!!!

  • @Siddhartha_Bose
    @Siddhartha_Bose 7 місяців тому +9

    Striver has taught us backtracking so well, this is question is a cake walk for us.😂

  • @vasachisenjubean5944
    @vasachisenjubean5944 10 днів тому

    10/10 lecture. Very useful

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

    Understood!
    Super awesome explanation

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

    Thanks bro for ur awesome work....BTW 16:41😋

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

    Great solution and explanation. Reminds me of print all subsubsequence problem.

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

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

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

    Very helpful video, thank you so much bhaiya!!

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

    without watching understood! ❤️ cause everyone knows why..

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

    Thanks man for the wonderful explanation, Grateful!

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

    Understood!!! awesome as usual

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

    Next level explanation!💥

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

    this series is too good!

  • @SachinKumar-zs6hm
    @SachinKumar-zs6hm 7 місяців тому

    Understood!! Thanks a lot Striver

  • @VarunMurthy-l9b
    @VarunMurthy-l9b 3 місяці тому

    These videos are incredible

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

    understood striver
    as always easy and great explanation

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

    Understood. Really wonderful lecture series.

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

    Backtracking explanation is fantastic

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

    This is an excellent explanation.

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

    Loved this video🎉

  • @ShahnazKhan-j4i
    @ShahnazKhan-j4i 5 місяців тому

    You are amazing, keep doing these

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

    I am glad that we have Striver❣he's real gem
    I expected ki mera Bf inti achi DSA padhata muje khud to amazon chla gaya
    Kash Striver mera bf hota ,but it okay ,i have Striver on utube , i am learning and growing

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

    brilliantly explained

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

    Great explanation!!

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

    op intuition and amazing concept!! tysm

  • @moonlight-td8ed
    @moonlight-td8ed 6 місяців тому +1

    it is an easy problem, just we have to get the logic of that we are in the same path, thank you STRIVER

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

    Thank you, Striver 🙂

  • @abytespaceneeded
    @abytespaceneeded 2 роки тому +23

    // single visited array code:
    class Solution {
    public:
    bool dfs(int s, vector &visited, vector adj[]) {
    visited[s] += 1;
    visited[s] += 1;
    for(int ele: adj[s]) {
    if(visited[ele] == 0) {
    if(dfs(ele, visited, adj) == true) return true;
    }
    else if(visited[ele] == 2) {
    return true;
    }
    }
    visited[s] -= 1;;
    return false;
    }
    // Function to detect cycle in a directed graph.
    bool isCyclic(int V, vector adj[]) {
    vector visited(V, 0);
    for(int i=0;i

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

    16:28
    bool dfs(int node, vector adj[], int vis[]){
    vis[node]=2;
    for(auto it:adj[node]){
    if(!vis[it]){
    if(dfs(it, adj, vis)==true)
    return true;
    }
    else if(vis[it]==2)
    return true;
    }
    vis[node]=1;
    return false;
    }
    //main function remains the same

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

    Great explaination 👍

  • @adithyab967
    @adithyab967 9 місяців тому +1

    C++ code using a single Visited array : bool dfs(vector adj[],vector&visited,int start){
    visited[start] = 1;
    int temp = visited[start];
    visited[start] = 2;
    for(auto &neighbour : adj[start]){
    if(visited[neighbour]==0){
    if(dfs(adj,visited,neighbour)==true) return true;
    }
    else if(visited[neighbour] == 2){
    return true;
    }
    }
    visited[start] = temp;
    return false;
    }
    bool isCyclic(int V, vector adj[]) {
    vectorvisited(V,0);
    for(int i=0;i

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

    Really ,youre taking us f/w..❤

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

    Understood!
    Wow 🤯

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

    Can we find the Cycle using BFs ?? In BFs we are not exploring in single path unlike in DFs, I think in BFs we cannot determine that we encountered the node in same path or not. Correct me if I am wrong

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

      We will have an algorithms for bfs as well in coming lectures

  • @kushalkollu8628
    @kushalkollu8628 2 місяці тому +1

    He is the OG

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

    blown away, understood

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

    understood very nicely sir great explaination sir

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

    mast video hai bhai 👌👌

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

    Understood, thank you so much.

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

    understood striver bhaiyaaaaa.................

  • @meghapaul1496
    @meghapaul1496 2 роки тому +26

    Using single vis array :
    class Solution {
    private:
    bool dfs(int node,vector adj[], vector&vis){
    vis[node]=2;
    for(auto it : adj[node]){
    if(!vis[it]){
    if(dfs(it,adj,vis)){
    return true;
    }
    }
    else if(vis[it]==2){
    return true;
    }
    }
    vis[node]=1;
    return false;
    }
    public:
    // Function to detect cycle in a directed graph.
    bool isCyclic(int V, vector adj[]) {
    // code here

    vectorvis(V,0);
    for(int i =0 ; i

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

      nice one

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

      isnt it same because any way you are using int data type for marking vis array which is already taking double space in comparison to bool data type?

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

      @@fivexx469 Yeah its same

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

    I completed the homework u gave in a min
    Thank u soo much for making it soo easyy!!!!
    U r a legend!!!

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

    understood! thanks a lot sir!

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

    Haven't seen the video yet but will definitely edit this comment to 'understood' after watching it. :) Thanks Striver Bhaiiyyaaaaaaaaaa

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

      i think you forgot ? go huuryy and edit this

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

      Hello bro... Waiting for your "Understood".

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

      Still wiating

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

      bhai dekh le video, placement season aa raha hai

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

      Bhai ab to samajh jaa...

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

    the idea of using just 1 array is amazing

  • @VenugopalaSwamy-fb3se
    @VenugopalaSwamy-fb3se 10 місяців тому +1

    instead of using path visited array we can use backtracking approach also

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

    Understood! thank you very much!!

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

    Understood 💯💯💯

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

    great crisp xplntion

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

    Thanks for the helpful tutorial! :)

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

    Great explaination

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

    Code using only single visited array:
    class Solution {
    bool util(vector adj[],int u,vector &vis){
    vis[u] = 1;
    for(auto v:adj[u]){
    if(vis[v] == -1){
    if(util(adj,v,vis))
    return true;
    }else if(vis[v] == 1)
    return true;
    }
    vis[u] = 0;
    return false;
    }
    public:
    // Function to detect cycle in a directed graph.
    bool isCyclic(int V, vector adj[]) {
    // code here
    vector vis(V,-1);
    for(int i=0;i

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

    You are a legend

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

    thanks striver🙌

  • @RS-zh1vc
    @RS-zh1vc 2 роки тому

    thank you Striver

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

    understoood

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

    understood, thank you!

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

    Striver bhaiya kindly fix the numbering for this particular video as it is showing at last instead of the order that this particular video has to be in..🙂🙂🙂🙃🙃

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

    Why is pathVis[i] set to 0 before exiting function? We are not passing pathVis by reference anyways. It will take the old state only.

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

      pathVis[] is an array not vector. Aarays are pass by reference

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

    Thank you Legend

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

    homework
    for only vis arr , we can take cnt as2 each time we visit(as it signifies vis +path) and while returning we could set it to 1 and if vis[node]&&vis[node]==2 return true;

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

    Just understood 😀

  • @DeadPoolx1712
    @DeadPoolx1712 Місяць тому +1

    UNDERSTOOD;

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

    Thank you sir

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

    Understood, Thanks

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

    why aren't we passing vis and pathVis by reference?I think after going back to prev function, we will loss data of vis

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

    great intitution

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

    I tried to output cycle path using path rray which you using ,
    in case of 4 vertex and edge as below
    1 2
    2 3
    3 4
    4 2
    Path array will give 1 2 3 4 but actual answer will be 2 3 4 only
    am i right ?

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

    Solution:
    class Solution {
    private:
    bool dfsCheck(int node, vector adj[], int visited[]){
    visited[node] = 2;
    for(auto it: adj[node]){
    if(visited[it] == 0){
    if(dfsCheck(it,adj,visited) == true){
    return true;
    }
    }
    else if(visited[it] == 2){
    return true;
    }
    }
    visited[node] = 1;
    return false;
    }
    public:
    // Function to detect cycle in a directed graph.
    bool isCyclic(int V, vector adj[]) {
    // code here
    int visited[V] = {0};
    for(int i = 0;i < V;i++){
    if(visited[i] == 0){
    if(dfsCheck(i,adj,visited) == true){
    return true;
    }
    }
    }
    return false;
    }
    };

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

    Thank you !!
    ☺☺☺☺☺

  • @Abhishek-sn9jm
    @Abhishek-sn9jm Місяць тому

    guruji tussi grt ho

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

    thank you so much and also understood

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

    Using one visited array
    bool dfs(int node, int vis[], vector adj[]) {
    vis[node] = 2;
    // visit adjacent nodes
    for(auto adjacentNode: adj[node]) {
    // unvisited adjacent node
    if(!vis[adjacentNode]) {
    if(dfs(adjacentNode,vis,adj))
    {
    return true;
    }
    }
    else if(vis[adjacentNode]==2) return true;
    }
    vis[node]=1;
    return false;
    }

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

    4:32 - in the same recursive stack

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

    I don't know if it's just me but Your keystrokes sounds funny🙃

  • @AnkitYadav-hx8im
    @AnkitYadav-hx8im Рік тому

    You should have made videos by doing some codes in c and some codes in java. That would be able to cater to both java and c students

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

    Understood❤

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

    Understood 😊

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

    Hey Striver, I have a request. Can you please put the java code in white bg? Its a little difficult to comprehend with the dark bg. Thank you!

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

      Sure, thanks will do it from the upcoming videos.

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

    Just Awesome

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

    we could have also created new boolean[V] for pathVis[] for each vertex instead of working with single array to save memory

  • @AdityaKumar-ow1rh
    @AdityaKumar-ow1rh 2 роки тому

    understood😊

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

    Understood...
    but you already have this topic covered in your Graph series...
    will that video be replaced by this..?
    Or is it a beginning of a new series altogether...?

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

    good one

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

    Great❤

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

    Why does it fail on Testcase 201, using java , using DFS. BFS passes all the testcases

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

    understood thank you

  • @DanielAmoateng-q8k
    @DanielAmoateng-q8k Рік тому

    Thank you!

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

    Hey java peeps, does this code gives a TLE on test case 201 / 410 ?