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

Поделиться
HTML-код
  • Опубликовано: 24 дек 2024

Комментарии • 368

  • @takeUforward
    @takeUforward  2 года назад +93

    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 10 месяцев назад

      yes

  • @mrbug100yearsago5
    @mrbug100yearsago5 2 года назад +48

    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 3 месяца назад +2

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

  • @beinghappy9223
    @beinghappy9223 2 года назад +159

    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 Месяц назад

      Visited pathVisited rocks

  • @yashgupta6797
    @yashgupta6797 2 года назад +23

    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 месяцев назад +7

    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 4 месяца назад +11

    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 3 месяца назад

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

    • @aniketainapur3315
      @aniketainapur3315 2 месяца назад

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

    • @saimasyeda6544
      @saimasyeda6544 2 месяца назад

      @@aniketainapur3315 OK thanks

  • @harshith4549
    @harshith4549 6 месяцев назад +3

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

  • @wolfpride9416
    @wolfpride9416 Год назад +3

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

  • @Siddhartha_Bose
    @Siddhartha_Bose 6 месяцев назад +9

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

  • @vishalsujaykumar5245
    @vishalsujaykumar5245 2 года назад +73

    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 7 месяцев назад +1

      @@santoshb7776 Yeah

    • @arnabsarkar5245
      @arnabsarkar5245 2 месяца назад

      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.

  • @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 🙏🏻❤

  • @oqant0424
    @oqant0424 2 года назад +2

    Understood!
    Super awesome explanation

  • @santanu29
    @santanu29 Год назад +1

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

  • @cypher7536
    @cypher7536 2 года назад +3

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

  • @stith_pragya
    @stith_pragya Год назад +1

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

  • @jewelchowdhury9752
    @jewelchowdhury9752 Год назад +1

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

  • @bhaktisharma9681
    @bhaktisharma9681 Год назад +1

    Very helpful video, thank you so much bhaiya!!

  • @anaghakr9900
    @anaghakr9900 Месяц назад

    Backtracking explanation is fantastic

  • @harshvardhansingh2272
    @harshvardhansingh2272 2 года назад +2

    understood striver
    as always easy and great explanation

  • @ketanjain3881
    @ketanjain3881 11 месяцев назад

    this series is too good!

  • @kingfisher7348
    @kingfisher7348 Год назад

    Next level explanation!💥

  • @sukhpreetsingh5200
    @sukhpreetsingh5200 2 года назад

    Understood!!! awesome as usual

  • @sumitchakrabortystudy651
    @sumitchakrabortystudy651 Год назад

    the idea of using just 1 array is amazing

  • @VarunMurthy-l9b
    @VarunMurthy-l9b 2 месяца назад

    These videos are incredible

  • @dipaligangawane980
    @dipaligangawane980 2 года назад

    Understood. Really wonderful lecture series.

  • @madhuryareddy3994
    @madhuryareddy3994 10 месяцев назад

    Thanks man for the wonderful explanation, Grateful!

  • @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

  • @uditech7736
    @uditech7736 8 месяцев назад

    This is an excellent explanation.

  • @SachinKumar-zs6hm
    @SachinKumar-zs6hm 6 месяцев назад

    Understood!! Thanks a lot Striver

  • @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

  • @kushalkollu8628
    @kushalkollu8628 2 месяца назад +1

    He is the OG

  • @preetisahani5054
    @preetisahani5054 Год назад

    brilliantly explained

  • @sivammohapatra1478
    @sivammohapatra1478 7 месяцев назад

    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

  • @preetichib2254
    @preetichib2254 11 месяцев назад

    Loved this video🎉

  • @ShahnazKhan-j4i
    @ShahnazKhan-j4i 4 месяца назад

    You are amazing, keep doing these

  • @chiranjiveethakur9889
    @chiranjiveethakur9889 Год назад

    Great explanation!!

  • @sripriyapotnuru5839
    @sripriyapotnuru5839 2 года назад

    Thank you, Striver 🙂

  • @abhignapalamoor1174
    @abhignapalamoor1174 Месяц назад

    Understood!
    Wow 🤯

  • @Desi_Debugger
    @Desi_Debugger 2 года назад

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

  • @manishprajapati8544
    @manishprajapati8544 2 года назад

    mast video hai bhai 👌👌

  • @ishangujarathi10
    @ishangujarathi10 Год назад

    op intuition and amazing concept!! tysm

  • @tecnicalworld6957
    @tecnicalworld6957 2 года назад

    Great explaination 👍

  • @p_s1dharth
    @p_s1dharth 6 месяцев назад

    blown away, understood

  • @parallax8916
    @parallax8916 Год назад

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

  • @jagratgupta8392
    @jagratgupta8392 Год назад

    understood very nicely sir great explaination sir

  • @syedmohdzeeshanali8247
    @syedmohdzeeshanali8247 2 года назад +12

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

    • @udaypratapsingh8923
      @udaypratapsingh8923 2 года назад +3

      i think you forgot ? go huuryy and edit this

    • @amaan6017
      @amaan6017 2 года назад +3

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

    • @babuchkjethia822
      @babuchkjethia822 6 месяцев назад +1

      Still wiating

    • @theganeshpatil
      @theganeshpatil 6 месяцев назад +1

      bhai dekh le video, placement season aa raha hai

    • @ashurajput6916
      @ashurajput6916 6 месяцев назад +1

      Bhai ab to samajh jaa...

  • @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

  • @DevashishJose
    @DevashishJose 11 месяцев назад

    Understood, thank you so much.

  • @jasminmalhot7829
    @jasminmalhot7829 10 месяцев назад

    Really ,youre taking us f/w..❤

  • @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

  • @DeadPoolx1712
    @DeadPoolx1712 23 дня назад +1

    UNDERSTOOD;

  • @sindhukambam
    @sindhukambam 2 года назад

    Understood! thank you very much!!

  • @KratosProton
    @KratosProton 2 года назад

    Great explaination

  • @thomasfrank132
    @thomasfrank132 Год назад

    You are a legend

  • @abhijeetkumar2970
    @abhijeetkumar2970 Год назад +1

    understoood

  • @Pranauv
    @Pranauv 9 месяцев назад

    understood! thanks a lot sir!

  • @Kartik-s8r
    @Kartik-s8r 8 месяцев назад +7

    BELOW IS THE CODE USING SINGLE VISITED ARRAY (VALUE=1 FOR VISITED & VALUE=2 FOR PATHVISITED)
    .
    .
    .
    .
    .
    class Solution {
    public:
    bool detectCycleDFS(int node, vector &visited, vector adj[]) {
    // Put node into Answer
    visited[node] = 1;
    visited[node] = 2; // pathVisited
    // Run DFS on all it's non-visited neighbours
    for(auto neigh:adj[node]) {
    if(!visited[neigh]) {
    if(detectCycleDFS(neigh, visited, adj)) return true; // If any one of the DFS calls returns a True, we keep on returning True
    } else if(visited[neigh] == 2) { // If a node is visited again on same path, cycle is detected (visited node is also pathVisited)
    return true;
    }
    }
    // On coming back, omit the node from pathVisited as path is gonna be different now
    visited[node] = 1;
    return false;
    }
    bool isCyclic(int V, vector adj[]) {
    vector visited(V, 0); // Behaves as both visited (value = 1) & pathVisited (value = 2)
    for(int i=0; i

    • @rahulnegi4027
      @rahulnegi4027 2 месяца назад

      bro just use visited[node] = 2; no need for the statement above it

  • @aayushgakhar3525
    @aayushgakhar3525 5 месяцев назад

    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;

  • @kr_ankit123
    @kr_ankit123 2 года назад +5

    I am glad that I am able to develop the logic and it has been possible after watching your lectures. Thanks a lot Striver.
    Solution without using path array:
    private:
    bool dfs(vector adj[],vector&vis,int node){
    vis[node]=1;
    for(int it:adj[node]){
    if(vis[it]==0){
    if(dfs(adj,vis,it))return true;
    }
    else{
    if(vis[it] == 1)return true;
    }
    // cout

    • @fluxcy2396
      @fluxcy2396 Год назад

      Your code is far far from optimal, infact its a brute-force solution. It's computing the same thing over and over again.
      Here's a correct solution in just a single visited array-
      2 means the node is in the current path
      Once we are returning after exploring a given path, we change visited[currNode] from 2 to 1
      Which means the current node is not in the current path anymore, however, it has been visited and does not have a cycle either
      ```
      class Solution {
      private:
      bool hasCycle(int currNode, vector adj[], int visited[]){
      visited[currNode] = 2;
      for(int nextNode : adj[currNode]){
      if(!visited[nextNode]){
      if(hasCycle(nextNode, adj, visited)) return true;
      }
      else if(visited[nextNode] == 2){
      return true;
      }
      }
      visited[currNode] = 1;
      return false;
      }
      public:
      bool isCyclic(int V, vector adj[]) {
      int visited[V] = {0};
      for(int node = 0; node < V; node++){
      if(!visited[node] && hasCycle(node, adj, visited)) return true;
      }
      return false;
      }
      };
      ```

  • @rohitanand7071
    @rohitanand7071 7 месяцев назад

    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;
    }

  • @RS-zh1vc
    @RS-zh1vc 2 года назад

    thank you Striver

  • @updownftw
    @updownftw 15 дней назад

    Thank you Legend

  • @adityasaxena6971
    @adityasaxena6971 Год назад

    Understood 💯💯💯

  • @herculean6748
    @herculean6748 2 года назад

    thanks striver🙌

  • @Abhishek-sn9jm
    @Abhishek-sn9jm 13 дней назад

    guruji tussi grt ho

  • @UECAshutoshKumar
    @UECAshutoshKumar Год назад +1

    Thank you sir

  • @Divas_Sagta_09
    @Divas_Sagta_09 Год назад

    4:32 - in the same recursive stack

  • @ramuchiluveru1056
    @ramuchiluveru1056 Год назад

    Thank you soo much bhayya.. for your wondefull explaination
    using the single visited array
    bool dfs(int node,vector adj[],vector visited)
    {
    visited[node]++; ..marking as visited
    visited[node]++; //marking its path by increment
    for(auto i: adj[node])
    {
    if (visited[i] == 0) {
    if(dfs(i, adj, visited))
    return true;
    }
    else if (visited[node] == 2)
    return true;
    }
    visited[node]--; //unpathing
    return false;
    }
    bool isCyclic(vector& edges, int v, int e)
    {
    // Write your code here
    vector adj[v];
    //creating adj list
    for(auto edge: edges)
    {
    int from = edge[0];
    int to = edge[1];
    adj[from].push_back(to);
    }
    vector visited(v,0);
    // vector path(v,0);
    for(int i=0;i

    • @AyushGupta-ux4gq
      @AyushGupta-ux4gq Год назад

      for(auto i: adj[node])
      {
      if (visited[i] == 0) {
      if(dfs(i, adj, visited))
      return true;
      }
      else if (visited[I] == 2)
      return true;
      }
      *CORRECT CODE*

  • @ambastaaashishkumarsanjayk2729
    @ambastaaashishkumarsanjayk2729 2 года назад

    Understood, Thanks

  • @StellarDev
    @StellarDev Год назад

    Thanks for the helpful tutorial! :)

  • @atharvadeshmukh6328
    @atharvadeshmukh6328 10 месяцев назад

    understood, thank you!

  • @KS0607
    @KS0607 Год назад

    great crisp xplntion

  • @monikagadewar4927
    @monikagadewar4927 2 года назад

    Just understood 😀

  • @peeyushpandey6664
    @peeyushpandey6664 Год назад

    Thank you !!
    ☺☺☺☺☺

  • @Piyushraj0
    @Piyushraj0 2 года назад

    Understood 😊

  • @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

  • @harkeshbirman
    @harkeshbirman 2 года назад

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

  • @suryakiran2970
    @suryakiran2970 Год назад

    Understood❤

  • @ayushthakur733
    @ayushthakur733 Год назад

    Great❤

  • @mathematics7746
    @mathematics7746 Год назад

    thank you so much and also understood

  • @DanielAmoateng-q8k
    @DanielAmoateng-q8k Год назад

    Thank you!

  • @AdityaKumar-ow1rh
    @AdityaKumar-ow1rh 2 года назад

    understood😊

  • @umeshkaushik710
    @umeshkaushik710 2 года назад

    Understood 🤠

  • @adithyab967
    @adithyab967 8 месяцев назад +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

  • @NiravRathod-p5n
    @NiravRathod-p5n Год назад

    space complexity of 2 boolean array < 1 int/short array

  • @aayushgakhar3525
    @aayushgakhar3525 5 месяцев назад

    great intitution

  • @subhadeepghosh2813
    @subhadeepghosh2813 2 года назад

    Maza aa gya vai

  • @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

  • @khyatikakkar9259
    @khyatikakkar9259 7 месяцев назад

    Understood sir

  • @Learnprogramming-q7f
    @Learnprogramming-q7f 7 месяцев назад

    Thank you bhaiya

  • @ANURAGSINGH-nl2ll
    @ANURAGSINGH-nl2ll Год назад

    understood thank you

  • @digvijay1228
    @digvijay1228 Год назад

    The moment i heard path, I stopped the video and coded the solution and it passed. Thanks to recursion playlist (subsequence pattern). DFS + subsequence.
    Understood!!!
    Code Reference:
    public boolean isCyclic(int V, ArrayList adj) {
    Set vis = new HashSet();
    for(int i=0; i

  • @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

  • @devanshupadhyay2658
    @devanshupadhyay2658 Год назад

    Best in the game aur isme do rai nahi !!

  • @VenugopalaSwamy-fb3se
    @VenugopalaSwamy-fb3se 9 месяцев назад

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

  • @_sf_editz1870
    @_sf_editz1870 6 месяцев назад

    so we just analyse the recurrsion stack if we visited that node again or not superb algorithm

  • @impatientgaming9868
    @impatientgaming9868 Год назад

    good one

  • @physicsmathsworld2033
    @physicsmathsworld2033 Год назад

    Understood !!