G-54. Strongly Connected Components - Kosaraju's Algorithm

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

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

  • @nakulmantri1235
    @nakulmantri1235 Месяц назад +6

    Undeniably the best teaching methodology and the content for strengthening DSA

  • @yashshukla1637
    @yashshukla1637 5 дней назад +2

    STRIVER OP. GOAT of DSA tutorials

  • @adithyabhat4770
    @adithyabhat4770 Год назад +15

    Your videos and the SDE sheet are helping me so much to brush up the DSA concepts and learn the ones I ignored in college. A BIG THANK YOU!!

  • @sahiltambe9085
    @sahiltambe9085 3 месяца назад +5

    Your explanation goes straight inn , such a brilliant teacher!!

  • @ashishpatel8325
    @ashishpatel8325 День назад

    Finally I have Completed Graph took 25 days thank you Striver , now I will be solving problems

  • @dishant930
    @dishant930 Год назад +32

    I think after seeing the video if you read the striver sheet explanation for the same question it will give you more insight since it is really well written. I really liked it!

  • @KUMARASHISHRANJAN
    @KUMARASHISHRANJAN Год назад +35

    The above code gave me `TLE`
    so, with few minor changes it will work for you.
    To optimize the given code, you can make a few changes to improve its efficiency:
    1. Pass the `adj` vector as a reference to the `dfs` function: Currently, the `adj` vector is passed by value, which creates a copy of the vector in each recursive call. Instead, pass it by reference to avoid unnecessary copies.
    2. Use a vector of vectors (`adjT`) instead of an array of vectors for the transpose graph: Declaring `vector adjT[V]` as a variable-length array may cause a stack overflow for large values of `V`. Instead, use a vector of vectors to represent the transpose graph (`adjT`).
    3. Reserve memory for the transpose graph vectors: Before pushing elements into `adjT`, reserve memory for each vector based on the size of the corresponding adjacency list in the original graph. This avoids frequent reallocations and improves performance.
    4. Use vectors instead of stacks: Instead of using a stack to store the finish times of the nodes in the first DFS, you can use a vector and append nodes at the end. This eliminates the need for reversing the stack later on.
    Here's the optimized code with these changes:
    Code :
    class Solution {
    private:
    void dfs(int node, vector& adj, vector& vis, vector& finishOrder) {
    vis[node] = 1;
    for (int it : adj[node]) {
    if (!vis[it]) {
    dfs(it, adj, vis, finishOrder);
    }
    }
    finishOrder.push_back(node);
    }
    void dfs2(int node, vector& adj, vector& vis) {
    vis[node] = 1;
    for (int it : adj[node]) {
    if (!vis[it]) {
    dfs2(it, adj, vis);
    }
    }
    }
    public:
    // Function to find the number of strongly connected components in the graph.
    int kosaraju(int V, vector& adj) {
    vector vis(V, 0);
    vector finishOrder;
    for (int i = 0; i < V; i++) {
    if (!vis[i]) {
    dfs(i, adj, vis, finishOrder);
    }
    }
    // Creating the transpose graph (adjT)
    vector adjT(V);
    for (int i = 0; i < V; i++) {
    vis[i] = 0;
    for (int it : adj[i]) {
    adjT[it].push_back(i);
    }
    }
    // Last DFS using the finish order
    int scc = 0;
    for (int i = V - 1; i >= 0; i--) {
    int node = finishOrder[i];
    if (!vis[node]) {
    scc++;
    dfs2(node, adjT, vis);
    }
    }
    return scc;
    }
    };
    These optimizations should improve the efficiency of the code.

  • @rishabhjain6272
    @rishabhjain6272 7 месяцев назад +6

    the first step is same as topo sort using dfs technique, will not work with bfs (khann's algo) due to directed cyclic graphs.but if you apply topo sort using dfs in directed cyclic graphs ,it will work.

  • @adebisisheriff159
    @adebisisheriff159 11 месяцев назад +7

    Honestly, this playlist deserves Millions views and comments..... Thanks for all you do Striver!!!

  • @cinime
    @cinime 2 года назад +11

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

  • @kushagrasrivastava1443
    @kushagrasrivastava1443 2 года назад +123

    I thought I was done with graphs 😅

    • @SomeshCodes
      @SomeshCodes 10 месяцев назад +4

      Literally me too...😅

    • @bharat_alok11
      @bharat_alok11 3 месяца назад +1

      @@SomeshCodes me too

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

    And here comes the real OG Striver.❤

  • @ShreyaLanka-1912
    @ShreyaLanka-1912 5 месяцев назад +2

    Understood!! Thank you for this amazing explanation.

  • @neelulalchandani7429
    @neelulalchandani7429 4 месяца назад

    Brilliant explanation! Thanks for the graph series, the best teacher ever!

  • @muskanchaurasia1532
    @muskanchaurasia1532 Год назад +2

    Just amazing.
    Great Explanation.

  • @andreasleonidou3620
    @andreasleonidou3620 Год назад +5

    Excellent tutorial and really helpful, thanks!!

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

    This is much intutive than the previous video on kosaraju(other graph playlist)

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

      Yes I read the comments, and then made this one.

    • @dhirendrasingh6071
      @dhirendrasingh6071 Год назад +6

      @@takeUforward you have changed the lives of so many students, you have blessings of many. ♥️

    • @tanmaypal2003
      @tanmaypal2003 Год назад +7

      ​@@takeUforward when we sort all the edges according to finishing time and store it in stack like this 0,1,2,3,4,5,6,7 , so instead of storing in stack can we use queue and then when we pop out elements from queue we start DFS from 7 instead of 0 and 7 is not connected to anyone so we found 1st SCC then we pop 6 and do DFS and found 2nd SCC then we pop 3 and do DFS and got 3rd SCC and so on. In this approach we don't need to reverse the graph. Can we do like this?

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

      @@tanmaypal2003 Nice observation. I think this should work fine.

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

      @@tanmaypal2003 yes

  • @Emperor723
    @Emperor723 7 месяцев назад +1

    mazaaaaaaa aaaaaaaagyaaaaaaaaaaa
    this is first time i have come across any of your videos
    der aaye par durust aaye....
    let me subscribe!

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

    Finally understood kosaraju algo. Thank you striver.

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

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

  • @vaishalidev6621
    @vaishalidev6621 3 месяца назад

    you are really good man!!! appreciate ur clarity of thoughts and words!! kudos and best wishes!!🎉

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

    thanks for the clear explanation of this complicated topic

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

    Going to end the graph..❤ understood

  • @Mr_Cat_11
    @Mr_Cat_11 2 года назад +6

    Long time no see sir 😊
    Thank you for posting 🥰🔥💖

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

    My Last graph question for this series 😊

  • @rohinianekar61
    @rohinianekar61 Год назад +2

    understood, nice explanation

  • @mraryanrajawat9693
    @mraryanrajawat9693 2 года назад +7

    class Solution
    {
    private:
    void dfs(int node,vectoradj[],vector&vis,stack&st) // dfs for adj
    {
    vis[node]=1;
    for(auto it:adj[node])
    {
    if(vis[it]==0)
    {
    dfs(it,adj,vis,st);
    }
    }
    st.push(node);
    }
    void dfs2(int node,vectoradjT[],vector&vis) // dfs for adjT
    {
    vis[node]=1;
    for(auto it:adjT[node])
    {
    if(vis[it]==0)
    {
    dfs2(it,adjT,vis);
    }
    }
    }
    public:
    //Function to find number of strongly connected components in the graph.
    int kosaraju(int V, vector adj[])
    {
    vectorvis(V,0);
    stackst;
    vector adjT[V]; // adj list after reversing edges
    for(int i=0;i

  • @rahulsangvikar7973
    @rahulsangvikar7973 8 месяцев назад +4

    Just realised one thing. You can avoid reversing the graph if you were to put the time in a queue instead of a stack.

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

      No you need stack cause if you use Queue it will keep going on to next SSC using the visited araay

    • @KeigoEdits
      @KeigoEdits 4 месяца назад

      exactly my thought

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

    Man, amazing explaination. Hats off to you buddy

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

    You are a very good teacher apse sikhna easy lagta hai

  • @AmanKumar-wd2mq
    @AmanKumar-wd2mq Год назад

    You explain so well ❤❤

  • @ManishKumar-zm9rj
    @ManishKumar-zm9rj Год назад +3

    We can use the same dfs again by passing a dummy stack:
    public void dfs(ArrayList adj, int[] vis, Stack st, int node){
    vis[node] = 1;
    for(int it : adj.get(node)){
    if(vis[it] == 0){
    dfs(adj, vis, st, it);
    }
    }
    st.push(node);
    }
    //Function to find number of strongly connected components in the graph.
    public int kosaraju(int V, ArrayList adj)
    {
    int[] vis = new int[V];
    Stack st = new Stack();
    for(int i = 0; i < V; i++){
    if(vis[i] == 0){
    dfs(adj, vis, st, i);
    }
    }
    ArrayList adjT = new ArrayList();
    for(int i = 0; i < V; i++) adjT.add(new ArrayList());
    for(int i = 0; i < V; i++){
    vis[i] = 0;
    for(int it : adj.get(i)){
    // previously: i -> it
    // Now make it: i i
    adjT.get(it).add(i);
    }
    }
    int scc = 0;
    while(!st.isEmpty()){
    int node = st.pop();
    if(vis[node] == 0){
    scc++;
    dfs(adjT, vis, new Stack(), node);
    }
    }
    return scc;
    }

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

    Man Striver ur incredible

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

    great work sir i just watch ur few video and ur content is awesome

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

    Thank you sir 🙏

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

    sorting according to finish time can be done using toposort:)

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

      that is toposort only. Toposort can be done using stack and that's what it is here.

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

      @abcsumit Toposort banega hi nahi, wo sirf DAG mein work karta hai.

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

      @@deviprasad_bal Toposort banega hi nahi, wo sirf DAG mein work karta hai.

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

      @@DheerajDivaker Yes you are right but here since graph can be cyclic as well as acyclic , so incase of CYCLIC one edge which is causing cycle is not stored , like 1->2->3->1 , is only stored as [ 1, 2 ,3 ] .
      So ultimately we should not call it as a toposort ,but implementation is exactly same.

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

      @@Anonymous_Coder yes absolutely correct.

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

    Thanks for Explaining the logic

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

    Understood after a little bit of effort.

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

    Thanks for Explaining this concept :) really liked your explaination

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

    Amazing content🔥

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

    Note: we can't say this as a Topological sort(as topological sort using DFS will get you stuck in Loop i.e cycle), but its a bit different. Its topological Sort for the SCC.

  • @abhinavraj1338
    @abhinavraj1338 8 дней назад +1

    Can we visit from 7 to 0 without reversing the graph will it work??

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

    Awesome work 👏

  • @mr.dependable4885
    @mr.dependable4885 2 года назад +5

    Why is it important to reverse the edges, can't we just start the dfs in reverse order ?
    Like in the example start from 7
    can any1 please explain

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

      we can't .try dryrun on 1st example ,
      suppose u created vector which store the timing then timing will be
      {1 2 4 3 0} if you try dfs accoording to this you still cannot find scc.

    • @shivamsangwan7268
      @shivamsangwan7268 2 года назад +1

      Yes, you can do that. But, this video is about Kosaraju's algorithm, which is implemented this way.

  • @sathvikmalgikar2842
    @sathvikmalgikar2842 10 месяцев назад +2

    guys just in case any one wondering why that stack of dfs calls was required that is only if u r solving for the second case of actually printing the components and not just finding number of components.
    like based on the stack trace u can make a note of elements while popping and put them into groups and print

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

      without using stack, how to do solve the first case of finding no. of compo? I mean to find no. of components also we need it in sorted way right?

    • @amansingh.h716
      @amansingh.h716 3 месяца назад

      @@vishalcheeti8374 we already reversed the graph so it will count the component for every dfs call,but somehow without stack its not working

  • @249abhi
    @249abhi Год назад

    awesome explanation!

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

    thank you very muchhh! You've literally changed so many lives ✌️

  • @space_ace7710
    @space_ace7710 Год назад +4

    GFG compiler giving TLE, don't know why?? :(

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

    🔥🔥🔥🔥
    Explanation

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

    maza aaala re ala striver aala

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

    amazing content!

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

    19:55 Why did you mention to write as private function. Is there any advantage of it over public. As I tested in run time and got public working faster than private. Also from outer source noone is calling that dfs function. So kindly elaborate please

  • @ms-ej4gd
    @ms-ej4gd 2 года назад

    Big fan of your work striver

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

    Understood, thanks!

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

    at 13:00 while traversing at scc1 from the node 0 using dfs you have taken the edges in the already present way(or say initial way) but since we have reversed the edges it should move in another way and you are also using the fact of of the edges being reversed at 13:05 when you are trying to access 3 from the dfs(2) you have said that . Then again same thing when doing same thing for dfs(3) we are not using the fact that edges are reversed. Can anyone here clear my doubt that where I am understanding it wrong?

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

      I get ur point , Striver used scc1->scc2->scc3->scc4 , Iniital config something like scc1scc3->scc4 can be used for better understanding

  • @-VLaharika
    @-VLaharika Год назад

    Understood 👍

  • @dhruvn6522
    @dhruvn6522 Год назад +2

    Sir is sorting edges according to finishing time same as topological sort?

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

      Will topological sort work in cyclic graphs?

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

    awsm explanation thank u so much

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

    Understood❤

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

    Awesome thanks a lot

  • @arnabsarkar5245
    @arnabsarkar5245 День назад

    3:16 Can anybody explain how 3 & 7 are SCC ?

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

    Understood Sir!

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

    How do I pick the starting node for sorting.
    In the above example if we would have started sorting from Node 3, I would have never reached 0, 1, 2. So how to calculate this increasing time for all nodes efficiently.

  • @UjjawalPathak-qy3uj
    @UjjawalPathak-qy3uj 6 месяцев назад

    HEY STRIVER, We can also reduce the time and steps if first getting there there finishing time and store in a queue rather then stack so because of FIFO we know first element to finish so we don't need to reverse the graph either we can directly go through the finishing elements which are already reverse with respect to graph it will reduce steps and clean code too.
    correct me if I m wrong

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

      yes you are wrong. on so many levels that it cant be fixed anymore.

  • @subrahmanyammartha9531
    @subrahmanyammartha9531 3 месяца назад

    @striver... is there really a need to reverse the graph...or the edges...
    After finding the finishing times and storing them....we could start dfs with the ascending order of finishing time....that would give us the 7th node first...then 6th....then 3rd and then 2nd..... this would give us 4 SCC and also the SCC ....may be just in a different order but still SCC

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

    amazing content

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

    please make videos on Eulerian paths also.

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

    Thanks🙌

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

    thanks for the video

  • @sharathkumar8338
    @sharathkumar8338 2 года назад +7

    Understood brother. Could you please upload videos on sliding window and 2 pointers?? I saw most amazon OA will be based on that only.

  • @adityavaste8963
    @adityavaste8963 Год назад +2

    Can we skip the step 1, and just reverse all the edges ? Because after reversing edges, components will be logically separated and we can run DFS on it separately, and can find the nodes in each component.
    Please can anyone guide me on this ?

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

      Ohh, got it. It's for the efficiency

    • @Jinxed192
      @Jinxed192 Год назад +2

      for eg, in the same example as striver's, if you reverse the edge between 2 & 3, with your process, when the graph is reversed, the dfs(0) has 3 as well in it, this is the loop hole. Whereas, in the algo, when we do dfs first and calculate finishing times, we get 3 at the top of the stack, so now we can make different dfs calls for each scc. Hope you understand. Have a great day!

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

      ​@@Jinxed192 Thanks for explaination.
      That means we must know from where to start, to void futher conflicts.

    • @VISHALMISHRA-ff2ih
      @VISHALMISHRA-ff2ih 4 месяца назад

      @@Jinxed192 the edge is like 0->1, 1->2 , 2->0 , 2->3 then how you are saying reversing the edges between 2->3 will be inside the dis(0)..And what Aditya is commenting is totally fine.

  • @ElderMoro
    @ElderMoro 2 года назад +1

    Thanks buddy

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

    thought process is very tricky

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

    Can't we use queue and then not reversing the edges and just count no of scc of back, but it's not working idk

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

      edges ko reverse karne se SCCs separate ho rahe hai..

  • @anagharaveendra53
    @anagharaveendra53 29 дней назад

    When we are finding out the time complexity of any algorithm, why isn't the lower bound also considered??
    Ideally speaking for the method of dfs, the time complexity is theta(V + E).
    So the time complexity of SCC must also be theta(V + E).

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

    mast padha dia bahiya

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

    reach++
    Loved it

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

    Isn't the first step same as topological sort?

  • @manikiran949
    @manikiran949 5 месяцев назад +1

    Isnt that stack thing, is topological sort ?

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

      The difference lies in the absence of a cycle in the original example, as per the definition of topological sorting. This implies that we should first check for cycles before attempting to find a topological sort. In the provided example, however, we are generating an order where nodes are arranged based on the time they were visited. This is facilitated by the algorithm's flow, which uses a visited array ensuring that each node is visited exactly once. If a cycle were detected during traversal, the algorithm would indicate this by returning false, signifying that a valid topological sort does not exist. In this context, the primary purpose is to populate the stack for subsequent manipulations and operations, rather than solely ensuring a strict topological order.

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

      Understanding this algorithm can be quite complex because it isn't solely reliant on the direction of traversal or the starting node for the initial DFS. Additionally, it doesn't guarantee visiting all nodes in a single DFS pass. The crucial aspect is how the algorithm manages to account for these complexities using the stack, even after performing edge reversals.
      The algorithm's sophistication lies in its ability to handle these scenarios by utilizing the stack effectively, ensuring that it accommodates inversions regardless of traversal direction or initial starting conditions.

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

      For example, let's consider SCC1, SCC2, SCC3, SCC4, SCC5. Suppose node 0 is in SCC3, and SCC3 leads to SCC4, and SCC4 leads to SCC5. However, SCC2 leads to SCC3, and SCC1 leads to SCC2.
      So, you start DFS from SCC3 and visit SCC4 and SCC5 in the first traversal. The stack will store them. During the initial DFS traversal, the backtrack keeps track of the order of elements in that stack and fills them in an order based on finishing time.
      Now, SCC2 and SCC1 are still unvisited, but here's the interesting part: in the next steps of DFS traversal, even though DFS is called for them later, they will finish before 0 in terms of finishing time. This is because the DFS for SCC2 and SCC1 starts after the DFS for 0 ends completely. Kosaraju ingeniously used iteration with backtracking to manage this complex traversal.
      When DFS is called to calculate SCC2 (the third step in the example), this time, since we have reversed the edges, DFS would not go to SCC3 as it normally would, because SCC3 couldn't reach SCC2 in the original direction (this aspect demonstrates the algorithm's elegance).
      Therefore, recursion and iteration work together seamlessly to make this algorithm effective.

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

      Imo , the best graph algorithm.

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

      @@hardikjuneja1 Thank you for detailed explanation bro 😃

  • @ronitkaushik4634
    @ronitkaushik4634 4 месяца назад

    whats the problem in doing only reversing thr edges and dfs. why store them in first?

  • @GANESHSINGH-uc1gk
    @GANESHSINGH-uc1gk 2 года назад

    crystal clear

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

    Instate on transposing the graph, can't we just start from the last node?
    someone please explain....

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

    Is there any relation in this algo and topo sort as we get reverse topo from stack

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

    understood

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

    Understood.

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

    understood sir

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

    amazing..

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

    Understooddd!!

  • @AryanMathur-gh6df
    @AryanMathur-gh6df Год назад

    UNDERSTOOD

  • @nikhil_squats
    @nikhil_squats 4 месяца назад

    is first step similiar to topo sort?

  • @Kupo3.0
    @Kupo3.0 Год назад

    Understood!

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

    understood 🥶

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

    understood💛💙💛

  • @dumpster-jackson
    @dumpster-jackson 8 месяцев назад

    Understood!!

  • @DeveshR-t1w
    @DeveshR-t1w Год назад

    hey striver can we do bfs to sort the graph according to their finishing time ? is it possible ?

  • @vardhanbolla-kz7xe
    @vardhanbolla-kz7xe Год назад +1

    This code is giving tle in gfg, the below code is same as what you thought
    class Solution
    {
    private:
    void dfs(int node, vector &vis,vector adj,stack &st)
    {
    vis[node]=1;
    for(auto it: adj[node])
    {
    if(vis[it]==0)
    {
    dfs(it,vis,adj,st);
    }
    }
    st.push(node);
    }

    void dfs1(int node, vector &vis, vector adjT[])
    {
    vis[node]=1;
    for(auto it: adjT[node])
    {
    if(vis[it]==0)
    {
    dfs1(it,vis,adjT);
    }
    }
    }
    public:
    //Function to find number of strongly connected components in the graph.
    int kosaraju(int V, vector& adj)
    {
    //code here
    vector vis(V,0);
    stack st;
    for(int i=0;i

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

      To resolve this issue, make sure that adjT is declared as a vector of vectors
      vectoradjT(V);

  • @anishraj66
    @anishraj66 Год назад +2

    bhaiya can,t we solve it by reversing the stack instead of reversing the graph

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

      stack reversal will reverse the finish time but reversing the graph does not allow us to go from one scc to another scc

  • @Rajat_maurya
    @Rajat_maurya 2 года назад +8

    why we need to sort, why can't we simply use ?
    for(int i=0;i

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

      same question

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

      Sorting makes you sure that you process those nodes first which lie at the end of a directed path. If you apply it randomly, you might start dfs from the start node or any node in the middle and will visit the nodes that are not a part of the SCC as well.

    • @amansingh.h716
      @amansingh.h716 3 месяца назад

      @@rahulsangvikar7973 but we already reversed the nodes and its not connected anymore ,,,also we have visited array so we can ignore already processed node

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

    I am confused about the first step of arranging nodes on their finishing times. I thought that instead just doing normal DFS on reversed graph skipping the first step might also work but it doesnt, Can anyone explain this with an example

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

      if you reversed the graph and then perform the dfs how will you be able to reach form[0,1,2] --> [3] so to tackle this we store them in a stack to remember their order form start to finish .

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

    Understood