G-21. Topological Sort Algorithm | DFS

  Рет қаралды 354,322

take U forward

take U forward

Күн бұрын

Пікірлер
@takeUforward
@takeUforward 2 жыл бұрын
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
@arjunrai8126
@arjunrai8126 2 жыл бұрын
Understood
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
@pulkitjain5159 0 seconds ago LET ME GIVE WHAT I UNDERSTOOD AS AN INTUTION Agar isko Task Completion ke perspective se dekhe such that if A -> B is like ki A wala task complete karne ke liye B wala task complete hona jaroori hai. toh hum dfs ke through bas yeh keh rahe hai ki dfs(task , completedTasks){ visited[task] = true; // mene yeh task karna start kardiya hai // par mujhe pata laga yeh task toh bakiyo pe dependent hai , toh phele mein unko khatam karke ata hu // let task on which my current task is dependend on be "dep". for( int dep : adj[ task ] ){ if(!visited[dep]){ // agae yeh dep abhi tak khatam nahi hua hai dfs(dep , completedTasks); // phele m isko complete kar leta hu } } // ab jab saare tasks jinpe mein depend karta hu khatam hogaye toh completedTask.push(task); }
@artofwrick
@artofwrick 11 ай бұрын
Why can't we add codes in comments?
@Saritha_Dhandapani
@Saritha_Dhandapani Ай бұрын
Understood, thanks a lot.
@srinayclg390
@srinayclg390 2 жыл бұрын
Many coder who know all this things but cannot explain well, but u r the different beast who can do both single handedly !!!!
@harshniteprasad5301
@harshniteprasad5301 2 жыл бұрын
Revising through this playlist before an interview is a bliss. INTUITION : incase you faced some trouble , taking in consideration the graph 1->2->3->4 we start with the dfs(1) we keep calling it for the adjacent nodes and at the very end we reach dfs(4) WHICH DOES NOT HAS ANY ADJ NODE, thus we put it in the stack stating that there is no node it needs to point after completion we push 3 in the stack stating that all the nodes pointed by 3 must already be the stack, same way we go up and at the end we push 1 in the stack stating that all the nodes pointed by 1 are already in the stack in a linear order. Linear order if a node v points to u then v comes first then u.
@sayandey2492
@sayandey2492 Жыл бұрын
And if it is reverse of topological ordering? Use Queue :P
@varunaggarwal7126
@varunaggarwal7126 Жыл бұрын
@@sayandey2492 by playing with where you place stack during recursion you can use stack only.
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
@pulkitjain5159 0 seconds ago LET ME GIVE WHAT I UNDERSTOOD AS AN INTUTION Agar isko Task Completion ke perspective se dekhe such that if A -> B is like ki A wala task complete karne ke liye B wala task complete hona jaroori hai. toh hum dfs ke through bas yeh keh rahe hai ki dfs(task , completedTasks){ visited[task] = true; // mene yeh task karna start kardiya hai // par mujhe pata laga yeh task toh bakiyo pe dependent hai , toh phele mein unko khatam karke ata hu // let task on which my current task is dependend on be "dep". for( int dep : adj[ task ] ){ if(!visited[dep]){ // agae yeh dep abhi tak khatam nahi hua hai dfs(dep , completedTasks); // phele m isko complete kar leta hu } } // ab jab saare tasks jinpe mein depend karta hu khatam hogaye toh completedTask.push(task); }
@sakshammisra189
@sakshammisra189 Жыл бұрын
@@varunaggarwal7126 exactly what i was thinking , the moment you insert the ele should be made at the start and not end , regular dfs is rev topo i guess ?
@akash_assist
@akash_assist 9 ай бұрын
great comments , it's okk for understanding, actually great but code is actually working in backtracking way, so not exactly fitting...... mtlb ki phle hum uss element ko khoj rhe hain jo sbpe dependent hain (dfs(1) agar dfs(2) ko call kr rha hain mtlb 1->2 ja skte hain mtlb ki 2 ko krne ke liye 1 ka hona jruri hain, lekin yha hum sbse phle 2 ko stack mein dalenge then 1 ko so that 2 sbse niche chala jaye,) isse jo kaam sbse phle krna hain, jo kisi pe dependent nhi hain wo top pe aajayega@@pulkitjain5159 this is from my understanding, please correct if i am wrong.🙏
@decepticonWave
@decepticonWave Жыл бұрын
The problem with this solution is that if you are given a directed graph that contains a cycle in the solution. The algorithm wont be able to detect, it will spill out an ordering which is wrong. But when using khans algorithm, you will be able to detect whether top. sort was possible or not.
@guptashashwat
@guptashashwat Жыл бұрын
+1
@tanyasingh2344
@tanyasingh2344 Жыл бұрын
Yeah but he already mentioned it is for Directed Acyclic Graph so it won't work in Graphs containing cycles.
@salmankhader1258
@salmankhader1258 Жыл бұрын
But you can check the size of your topological sort array and if it is equal to number if vertices it is a valid one otherwise not.
@kartikdalai7998
@kartikdalai7998 Жыл бұрын
C ho tum
@uditgarg6508
@uditgarg6508 Жыл бұрын
that is completely wrong@@salmankhader1258
@AquaRegia-i3u
@AquaRegia-i3u Жыл бұрын
Quick Tip : If you are thinking, why don't we put into list when you start dfs, this way we don't have to use stack or reverse order. Consider a case 6->0->1->2->3->4->5, we start from 0 and put into list, so ordering comes out to be, 0,1,2,3,4,5 and then we check for 6, so 6 at last, but this is wrong. Hence we cannot put into list when starting the dfs, because we dont' know if 0 was coming from somewhere else. Hence we put into list at last and then reverse(or use stack and pop). So ordering becomes 5->4->3->2->1->0 and then we check for 6, so 5->4->3->2->1->0->6 and reversing this is correct topo.
@vinayjangra1401
@vinayjangra1401 Жыл бұрын
Thanks bro !!
@crosswalker45
@crosswalker45 Жыл бұрын
Why 6 cannot be in last?
@AquaRegia-i3u
@AquaRegia-i3u Жыл бұрын
@@crosswalker45 Because 6 is at starting of topo sort and not last. It is even before 0, since we started from 0 doesn't mean our topo start from 0.
@imPriyansh77
@imPriyansh77 7 ай бұрын
Thanks
@ChiragDhamija-b4n
@ChiragDhamija-b4n 6 ай бұрын
Hey striver Instead of using a stack we can directly store it in a vector and write ans.push_back(node) and just when returning the final anwerr we can reverse this vector This will help us to optimize the space complexity
@tummalapallikarthikeya2412
@tummalapallikarthikeya2412 3 ай бұрын
yeah! same opinion
@awesome_latest_virals6098
@awesome_latest_virals6098 Жыл бұрын
we can use bool array instead of int array to mark visited....it will take less memory.
@SD-vk3ko
@SD-vk3ko 2 жыл бұрын
Hey Striver, Thank you for the amazing content. But I request if you could add some problems on Union Find as well. Thanks in advance!!!
@hah314
@hah314 Жыл бұрын
Can't express it in words, your content is out of the world, really amazing bro❤❤
@vineetatiwari5060
@vineetatiwari5060 3 ай бұрын
One corner case - Say if we get nodes in queue that have 0 indegree plus 0 adjacent node as well, this will give us incomplete answer. 10 9 dhhid dahi cedg fg gdah i gbdei hbgf e ddde Here, in queue -> 0,1,9 will be added and none of them will have adjacent nodes as well so our answer will become incomplete. So always check the length of your topo answer whether its equal to k or not. If it is equal then return the string otherwise empty string. PS - We can use visited array also here.
@gopichandreddy7598
@gopichandreddy7598 4 күн бұрын
give on more clear example on the corner case, and also don't forget to provide the expected and actual output.
@arushimathur7205
@arushimathur7205 Жыл бұрын
Great Work Striver. Thanks for always helping us !!
@ishangujarathi10
@ishangujarathi10 Жыл бұрын
loved the intuition and explanation striverr bhaii
@NinjaPlayer005
@NinjaPlayer005 3 ай бұрын
Making graph feel as easy as binary search something only very few like striver can do!
@cinime
@cinime 2 жыл бұрын
Understood! Super amazing explanation as always, thank you very much!!
@the_curious_engineer
@the_curious_engineer 6 ай бұрын
whenever your heart is broken , don't ever forget you are golden..
@yashcoder291
@yashcoder291 2 ай бұрын
golden nhi , goal then
@the_curious_engineer
@the_curious_engineer 2 ай бұрын
@@yashcoder291 thanxx for correcting.
@stith_pragya
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video.................🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@shyren_more
@shyren_more 2 жыл бұрын
understood, was able to code up using the logic after your explanation, thanks!
@sanchitkaul5084
@sanchitkaul5084 3 күн бұрын
Nice Explanation! Looks like your energy was low in this video , but I guess thats the right amount of energy to have . over energetic is a waste of breath and time. Just a well wisher with constructive criticism . Good Work Striver !
@CodeMode9313
@CodeMode9313 Жыл бұрын
explained in quite easy manner ..thanks habibi
@dsa_tutorial
@dsa_tutorial Жыл бұрын
Thank you striver for providing such nice content
@pulkitjain5159
@pulkitjain5159 Жыл бұрын
LET ME GIVE WHAT I UNDERSTOOD AS AN INTUTION Agar isko Task Completion ke perspective se dekhe such that if A -> B is like ki A wala task complete karne ke liye B wala task complete hona jaroori hai. toh hum dfs ke through bas yeh keh rahe hai ki dfs(task , completedTasks){ visited[task] = true; // mene yeh task karna start kardiya hai // par mujhe pata laga yeh task toh bakiyo pe dependent hai , toh phele mein unko khatam karke ata hu // let task on which my current task is dependend on be "dep". for( int dep : adj[ task ] ){ if(!visited[dep]){ // agae yeh dep abhi tak khatam nahi hua hai dfs(dep , completedTasks); // phele m isko complete kar leta hu } } // ab jab saare tasks jinpe mein depend karta hu khatam hogaye toh completedTask.push(task); }
@noob_coder8926
@noob_coder8926 7 ай бұрын
nice explanation
@jotsinghbindra8317
@jotsinghbindra8317 6 ай бұрын
ek dum sexy explanation bhai!
@kunalarora3885
@kunalarora3885 6 ай бұрын
Very clearly explained @pulkitjain5159, @striver this is what you call intuition
@imafraidjumitebeeinnagang3886
@imafraidjumitebeeinnagang3886 5 ай бұрын
Should have just read this instead of watching the video, so good!
@parthivsinhvaghela6100
@parthivsinhvaghela6100 4 ай бұрын
it is like deadlock
@suryanshsingh6423
@suryanshsingh6423 6 ай бұрын
Understood. Fantastic explanation❤
@hercules3150
@hercules3150 2 жыл бұрын
Thank you sir iski bahut need thi. Haal hi mai ek question aaya tha aur woh mai nhi kar paya tha
@sripriyapotnuru5839
@sripriyapotnuru5839 2 жыл бұрын
Thank you, STRIVER 🙂
@AppaniMadhavi
@AppaniMadhavi 7 ай бұрын
Even without taking a stack we can do, it is by taking a vector and storing all the node values after completion of that node's dfs, and finally reverse that vector...
@harshith4549
@harshith4549 6 ай бұрын
Why to go all the way to reverse a vector rather than storing it in the reverse order during the dfs. Just create a vector with size of total number of nodes and using a index variable move from the back of vector to the front during dfs. Here's how its done: class Solution { private: void dfs(int start,int vis[],vector adj[],vector& ans,int& index){ vis[start]=1; for(auto it: adj[start]){ if(!vis[it]){ dfs(it,vis,adj,ans,index); } } ans[index--]=start; // Its decrement } public: //Function to return list containing vertices in Topological order. vector topoSort(int V, vector adj[]) { // code here int vis[V]={0}; vector ans(V); int index=V-1; for(int i=0;i
@abhijeetkumar2970
@abhijeetkumar2970 Жыл бұрын
The intuition behind the problem: The hint here lies in the definition of topological sort as we need the least dependent element first we add it at last(thus using stack). When a node finishes all it's calls, all the elements that should come after it would already be inserted to the stack and now we only need to add current node to the stack. Thus we can be confident about adding node to stack as all it's children are already processed.
@artofwrick
@artofwrick 11 ай бұрын
A > B >C and A>D>C. How does that work with a stack?
@abhijeet19403
@abhijeet19403 11 ай бұрын
​@@artofwrick At first make the adjacency list A- B,D B- C D- C Also make a visited array Start traversing from A to D At first A is not visited so mark it visited and call it's neighbors As B has also one neighbor we call it C has no neighbors (or child nodes) so the dfs stops and we add C to the stack Then B is added as now it has no more children Then D is called from A D tries calling it's children (C here) but it is already visited so we simply add D to stack At the end A is also added to the stack Thus the final contents of the stack are A D B C which is a valid topo sort
@lanslord11
@lanslord11 8 ай бұрын
Intuition part is what made this whole video amazing for meeee
@Saurabh-fe2bg
@Saurabh-fe2bg Жыл бұрын
got it!! thanks for this series
@GeetainSaar
@GeetainSaar 5 ай бұрын
Happy guru purnima ❤🎉
@rutikjalhare6836
@rutikjalhare6836 Жыл бұрын
GOD level explanation
@prajaktachachad477
@prajaktachachad477 9 ай бұрын
Amazingly explained :)
@rishabhgupta9846
@rishabhgupta9846 2 жыл бұрын
understood,great explanation
@lonersunited
@lonersunited 11 ай бұрын
Understood 😊
@pranayjain._
@pranayjain._ Жыл бұрын
Understood! Thank you sir
@vakhariyajay2224
@vakhariyajay2224 2 жыл бұрын
Thank you very much. You are a genius.
@vaalarivan_p
@vaalarivan_p Жыл бұрын
4:05 - 7:50
@shubhranginidas6818
@shubhranginidas6818 8 ай бұрын
We should apply the DFS way of Topological Sorting only if the ordering of the resulting sort is checked otherwise should always prefer BFS way of Topological Sorting. WHY? Because if the cycle exists DFS would return all the vertices with wrong ordering but in case of BFS, it wouldn't return all the vertices if cycle exists. So even if we don't go for ordering detection, number of vertices itself would clear whether sorting is possible or not. This is the reason why BFS (Kahn's Algorithm) is preferred.
@antor.morsalin
@antor.morsalin 4 ай бұрын
Amazing Explanation
@himaniupadhyay8201
@himaniupadhyay8201 Жыл бұрын
Thank You sooo much SIR 🙏
@kaichang8186
@kaichang8186 4 ай бұрын
understood, thanks for the great video
@yashsaxena7787
@yashsaxena7787 Жыл бұрын
g.addEdge(1,2); g.addEdge(1,3); g.addEdge(2,4); g.addEdge(2,5); g.addEdge(3,6); g.addEdge(3,7); why not working for this graph?????
@yashsaxena7787
@yashsaxena7787 Жыл бұрын
#include #include #include using namespace std; class Graph{ private: int V; vectoradj; void topologicalSortUtil(int v, vector&visited , stack&stack){ visited [v]=true; for(int i:adj[v]){ if(!visited[i]){ topologicalSortUtil(i,visited,stack); } } stack.push(v); } public: // constructor to initialize the graph with the number of vertices Graph(int vertices){ V=vertices; adj.resize(V); } void addEdge(int u,int v){ adj[u].push_back(v); } vector topologicalSort(){ vector visited (V,false); stackstack; for(int i=0;i
@imPriyansh77
@imPriyansh77 7 ай бұрын
It's working...
@ajith4249
@ajith4249 Жыл бұрын
In Reverse Order # another approach class Solution: #Function to return list containing vertices in Topological order. def topoSort(self, V, adj): # Code here stack=[] def dfs(node,adj,stack,vis): vis[node]=1 for item in adj[node]: if vis[item]==0: dfs(item,adj,stack,vis) stack.insert(0,node) vis=[0 for i in range(V)] for i in reversed(range(V)): if(vis[i]==0): dfs(i,adj,stack,vis) return stack
@Maunil2k
@Maunil2k 7 ай бұрын
I believe we need to assume that the given directed graph does not contain any cycle, only then this algorithm using DFS will work.
@DevashishJose
@DevashishJose 11 ай бұрын
Understood, Thank you so much
@shubhipaul6830
@shubhipaul6830 6 ай бұрын
For a long time I believed topo sort to be hard. Guess one just has to find the right explanation.
@utkarshsharma1185
@utkarshsharma1185 2 жыл бұрын
understood bhaiya..
@tasneemayham974
@tasneemayham974 10 ай бұрын
THANK YOUUU STRIVERRR!!
@CHOWDAVARAPUSAIDEEPAK
@CHOWDAVARAPUSAIDEEPAK 4 ай бұрын
Given , the algorithm achieves the desired output of topologically sorted array , but there can be many no of possible array sequences that are valid for the same graph . So , How do i get an array that's topologically and lexicographically sorted too?
@yuvrajanand9342
@yuvrajanand9342 Жыл бұрын
only had to watch half of the video and did the coding part all by myself
@kamikaze9245
@kamikaze9245 2 жыл бұрын
Understood bhaiya
@swaraj.nalawade.4634
@swaraj.nalawade.4634 3 ай бұрын
class Solution { private: void dfs(int start, vector adj[], int vis[], stack &st){ vis[start] = 1; for(auto &it : adj[start]){ if(!vis[it]){ dfs(it, adj, vis, st); } } st.push(start); } public: //Function to return list containing vertices in Topological order. vector topoSort(int V, vector adj[]) { int vis[V] = {0}; stack st; vector ans; for(int i=0; i
@DeepanshiBhardwaj-y1t
@DeepanshiBhardwaj-y1t 5 ай бұрын
Very Well Understood!!
@worthlessguy1621
@worthlessguy1621 9 ай бұрын
understood the assignment :)
@UECAshutoshKumar
@UECAshutoshKumar Жыл бұрын
Thank you sir 😊
@AyushGupta-ux4gq
@AyushGupta-ux4gq Жыл бұрын
at 5:39 ohh thats all lets code void dfs(int node,vector adj[],vector &visited,stack &st) { if(visited[node]==1) { return; } else { visited[node]=1; for(int i=0;i
@amitp277
@amitp277 Жыл бұрын
Awesome work
@evilpollination1916
@evilpollination1916 8 ай бұрын
Understood Striver bhai. Aapne samjhaya hai toh samjh to aayega. Also bhai aapki tabayt kharab lag rahi thi . Pls take care bhai.
@Rieshu-l9i
@Rieshu-l9i 9 ай бұрын
#Striver rocks 🤟👍
@kunal4710
@kunal4710 2 жыл бұрын
UNDERSTOOOOOD😊
@Learnprogramming-q7f
@Learnprogramming-q7f 8 ай бұрын
Thank you bhaiya
@amanasrani6405
@amanasrani6405 8 ай бұрын
understand bhaiya❤🙏🏻\
@tushar_kesharii
@tushar_kesharii Жыл бұрын
FOR REVIEWING THE CODE FOLLOW THIS - class Solution { private: void DFS(int start, vector&visited, vector adj[] , stack&stack){ visited[start]=1; for(auto x:adj[start]){ if(!visited[x]){ DFS(x,visited,adj,stack); } } stack.push(start); } public: //Function to return list containing vertices in Topological order. vector topoSort(int V, vector adj[]) { // declaring a visited array and initially filled with 0 vectorvisited(V,0); stackstack; for(int i=0;i
@Tbm4545
@Tbm4545 9 күн бұрын
Hlw means this is similar to dfs only difference is here we use a xtra stack to get topo sequence
@manishprajapat9135
@manishprajapat9135 2 жыл бұрын
@take U forward before applying this method we should ensure that no cycle is present ??
@VIRAJBHOSLE
@VIRAJBHOSLE 2 жыл бұрын
Input is always DAG, so it's not checked. But if input can be cyclic graph, you need to add cycle checks
@imPriyansh77
@imPriyansh77 7 ай бұрын
@@VIRAJBHOSLE Yeah, thanks!!!
@bro_code3505
@bro_code3505 2 жыл бұрын
hey striver I want to code like you!!
@yashshukla1637
@yashshukla1637 22 күн бұрын
So So So good!
@anssha2643
@anssha2643 Жыл бұрын
Why aren't we using the path[] here? Is it because its acyclic graph?
@user-fx3bn4co5o
@user-fx3bn4co5o 2 жыл бұрын
Its awesome bro
@kirtitung4877
@kirtitung4877 2 жыл бұрын
understood!!! JOD
@valarmorghulis9244
@valarmorghulis9244 Жыл бұрын
What I understood from this problem is that "GIve a BFS path using DFS". Is it?
@vinaynalluri277
@vinaynalluri277 2 жыл бұрын
everything is nyc except one thing sir if suppose i/p is loop(1,2,3) then s.size==n fails only bfs accepts am i correct i chckd for conditions
@banothutharun2743
@banothutharun2743 5 ай бұрын
understood striver bro
@akshatpandey2609
@akshatpandey2609 2 жыл бұрын
can we pushback the node in ans in the postorder of the dfs function i.e., after the for-loop?
@rohit2571
@rohit2571 2 жыл бұрын
then you have to reverse the stack.
@sanadkhan1
@sanadkhan1 2 жыл бұрын
kzbin.info/www/bejne/bIfMZoealMZreJo&ab_channel=Pepcoding watch this for your doubt clarification
@sakshammisra189
@sakshammisra189 Жыл бұрын
intuition is that we want reverse of the DFS as when dfs is completed then we are inserting which tells us A->B , then we are inserting B and then A , but we reverse it to get A and then B .
@mananarora141
@mananarora141 Жыл бұрын
UNDERSTOOD!!!!!!!
@saranavinash9261
@saranavinash9261 Жыл бұрын
You should have included or referred to the graph representation, so that we can get idea about how the adjacent nodes are stored and traversed.
@AdityaKumar-uf5xp
@AdityaKumar-uf5xp 2 жыл бұрын
understood but striver I forgot those code and have to remember everytime . How should I keep remember the code?
@diksha3157
@diksha3157 2 жыл бұрын
Don't memorise the code. Instead, try to understand the logic and then write code. Converting logic into code requires practice.
@Moch117
@Moch117 Жыл бұрын
Memorize the logic. If DFS, and topological sort, use a stack. BFS, use Queue. Both use visited array
@shivendrasingh8520
@shivendrasingh8520 6 ай бұрын
can we use queue in this question at last we will reverse the queue
@bestsaurabh
@bestsaurabh 2 ай бұрын
vis array was not passed as reference, still it worked???
@suryakiran2970
@suryakiran2970 Жыл бұрын
Understood❤
@UmeshYadav-qx4hr
@UmeshYadav-qx4hr Жыл бұрын
link is not found for -C++/Java/Codes and Notes Link Please check.
@bro_code3505
@bro_code3505 2 жыл бұрын
how do we know that stack will be used
@narendrarokkam5367
@narendrarokkam5367 2 жыл бұрын
Because we need to get in reverse order
@soumyamondal
@soumyamondal 2 жыл бұрын
@@narendrarokkam5367 we can store it in a vector then simply reverse it, space saved right?
@babai2196
@babai2196 Жыл бұрын
@@soumyamondal but time inc
@The_Shubham_Soni
@The_Shubham_Soni Жыл бұрын
UNDERSTOOD.
@gurudekirtaniye9001
@gurudekirtaniye9001 Жыл бұрын
Understood but what the intuition ?
@cypher7536
@cypher7536 2 жыл бұрын
understood ❤️
@MindsetMotivation75
@MindsetMotivation75 2 жыл бұрын
is it ok to use queue rather than using a stack ?
@Shivanai_h
@Shivanai_h 2 жыл бұрын
Yes but at last when you pop out nodes, you will have to reverse the resultant list.
@MindsetMotivation75
@MindsetMotivation75 2 жыл бұрын
@@Shivanai_h thank you 😊
@soumyamondal
@soumyamondal 2 жыл бұрын
@Ayush Negi simply use vector, and reverse it. No need to store again to vector from deque while returning.
@harshmishra5331
@harshmishra5331 Жыл бұрын
Why can we not use simple array instead of stack. I am not able to understand of specific stack in this case. Can any body clear this?
@TheBillionairesWorld
@TheBillionairesWorld Жыл бұрын
Yes we can push into vector..... Than at the end we can reverse it
@sumerrawat6947
@sumerrawat6947 2 жыл бұрын
Understood !
@saurabhpandey4427
@saurabhpandey4427 Жыл бұрын
class Solution { public: void dfs(int node, vector &Vis, stack &st, vector &adj) { Vis[node] = true; for (auto neighbor : adj[node]) { if (!Vis[neighbor]) { dfs(neighbor, Vis, st, adj); } } st.push(node); } bool isPossible(int N, int P, vector &prerequisites) { vector adj(N); for (auto pre : prerequisites) { adj[pre.second].push_back(pre.first); } stack st; vector Vis(N, false); for (int i = 0; i < N; i++) { if (!Vis[i]) { dfs(i, Vis, st, adj); } } stack reversedSt; // Stack to reverse the order while (!st.empty()) { reversedSt.push(st.top()); st.pop(); } return N == reversedSt.size(); } };....why this code is not working for prerequisites problem ?
@subhadeepghosh2813
@subhadeepghosh2813 2 жыл бұрын
maza aa gya
@harshdasila6680
@harshdasila6680 2 жыл бұрын
understoooddddd
@abhinavkohli4293
@abhinavkohli4293 Жыл бұрын
what if i run this algo on a directed graph with cycle
@imPriyansh77
@imPriyansh77 7 ай бұрын
Topological Sorting - DFS algorithm will print wrong linear ordering if input is a directed cyclic graph.
@soicooc3500
@soicooc3500 8 ай бұрын
5:30
@GeneralistDev
@GeneralistDev Жыл бұрын
Stack is not necessary. We could have used a vector also
@imPriyansh77
@imPriyansh77 7 ай бұрын
but need to reverse the array
@soicooc3500
@soicooc3500 8 ай бұрын
4:08
@heybuddy_JAI_SHREE_RAM
@heybuddy_JAI_SHREE_RAM Жыл бұрын
grt vdo
@saikrishna872
@saikrishna872 Жыл бұрын
UNDERSTOOD
@per.seus._
@per.seus._ 11 ай бұрын
understoood
@arkasheikh3539
@arkasheikh3539 2 жыл бұрын
"UNDERSTOOD"
@DeadPoolx1712
@DeadPoolx1712 Ай бұрын
UNDERSTOOD;
G-22. Kahn's Algorithm | Topological Sort Algorithm | BFS
13:50
take U forward
Рет қаралды 283 М.
Topological Sort Algorithm | Graph Theory
14:09
WilliamFiset
Рет қаралды 486 М.
BAYGUYSTAN | 1 СЕРИЯ | bayGUYS
36:55
bayGUYS
Рет қаралды 1,9 МЛН
Quilt Challenge, No Skills, Just Luck#Funnyfamily #Partygames #Funny
00:32
Family Games Media
Рет қаралды 55 МЛН
Top K Elements in 6 minutes | LeetCode Pattern
6:23
AlgoMasterIO
Рет қаралды 4,7 М.
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Codebagel
Рет қаралды 467 М.
Fastest Way to Learn ANY Programming Language: 80-20 rule
8:24
Sahil & Sarra
Рет қаралды 944 М.
3 Types of Algorithms Every Programmer Needs to Know
13:12
ForrestKnight
Рет қаралды 517 М.
G-19. Detect cycle in a directed graph using DFS | Java | C++
17:22
take U forward
Рет қаралды 267 М.