Тёмный

Topological Sort Algorithm | Graph Theory 

WilliamFiset
Подписаться 175 тыс.
Просмотров 449 тыс.
50% 1

How to find the topological sort of a directed acyclic graph
Shortest path on a Directed Acyclic Graph (DAG):
• Shortest/Longest path ...
Github source code link:
github.com/williamfiset/algor...
0:00 Intro
0:18 Topological sort real life examples
2:49 Technical definition of topsort
3:42 The need for directed acyclic graphs
4:46 Topological ordering of trees
5:26 Topological sort algorithm
9:28 Topological sort source code
==================================
Practicing for interviews? I have used, and recommend `Cracking the Coding Interview` which got me a job at Google. Link on Amazon: amzn.to/3cvMof5
A lot of the content on this channel is inspired by the book `Competitive Programming` by Steven Halim which I frequently use as a resource and reference. Link on Amazon: amzn.to/3wC2nix
Support me by purchasing the full graph theory course on Udemy which includes additional problems, exercises and quizzes not available on RU-vid:
www.udemy.com/course/graph-th...

Опубликовано:

 

29 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 161   
@OzoneX4
@OzoneX4 6 лет назад
Clear, concise, great animation! Thank you so much buddy.
@paranormaledits9526
@paranormaledits9526 Год назад
I read comments before watching a tutorial, thanks for the comment.
@translucentleaf6163
@translucentleaf6163 4 года назад
The world needs more heroes like you who can spend less than 15 minutes explaining what takes certain professors at least two hours. This was really intuitive for both newcomers and detailed enough to actually wrote code with it. Thank you!
@patrickchan7891
@patrickchan7891 4 года назад
Omg!You are just the perfect one demonstrating these concepts so clearly.It's really friendly for beginners to learn.Thank you very much!
@notalex01
@notalex01 3 года назад
These tutorials are excellent. I wish I could thumbs up 10 times. I'm studying for coding interviews and this is the best tool I have come across for understanding graph theory problems.
@saravanprathi6956
@saravanprathi6956 4 года назад
The way you explain stuff visually helps me understand the algorithms well. Thanks a ton!
@dirkvanbeveren5042
@dirkvanbeveren5042 6 лет назад
This is a great tutorial! Really well explained; visually and in detail.
@norcal6181
@norcal6181 5 лет назад
Thank you for this. I have a final in my Data Structures and Algorithms course today, and I didn't understand this subject. Now I do. Thank you.
@XahhaTheCrimson
@XahhaTheCrimson 2 года назад
Mentioning not only DAG but Tree gives me a lot of intuitions... That's why I watch this channel even after I graduated and got a job. Studying never ends definetly. Thank you William.
@mohsinhayatt
@mohsinhayatt 5 лет назад
This is the best explanation video for a graph algorithm. Can't get any better
@miltonhuynh4209
@miltonhuynh4209 5 лет назад
I understood enough to complete my quiz at 1:06, great video!
@PiyushSharma95
@PiyushSharma95 4 года назад
Thanks William. Watched the whole MIT DFS class for Topological sort, finally understood it here.
@aalekhpatel8995
@aalekhpatel8995 4 года назад
I understand that I’m a bit late to the party but this is genuinely a brilliant explanation of Top Sort! Thank you so much!❤️❤️
@aryangod2003
@aryangod2003 7 месяцев назад
Finally understood it, much clearer than the exposition in my class. I now understand even why it works to give a topological ordering based on how you pop the call stack.
@akshaymalhotra597
@akshaymalhotra597 5 лет назад
The best explanation I could find online!
@SrushtiPawar-vi6ns
@SrushtiPawar-vi6ns 5 месяцев назад
The number of times I have watched this video and number of times I have forgotten this concept is really funny!
@mrisaacs3089
@mrisaacs3089 4 года назад
Another great mind at explaining things the way I like to understand them. First video I've seen on your channel. Instant subscribe and set notification on 'All'!
@WilliamFiset-videos
@WilliamFiset-videos 3 года назад
Hello everyone, I released another video on how to find the topological sort of a graph using Khan's algorithm (which is arguably easier to understand than the DFS solution IMO): ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-cIBFEhD77b4.html
@z08840
@z08840 3 года назад
I have a question regarding ordering list - isn't it unnecessary to pass index i back and forth? can we just say that ordering is backward and just push back nodes into it?
@Shreyas535
@Shreyas535 2 года назад
@@z08840 We can just reverse the list before returning it.
@z08840
@z08840 2 года назад
​@@Shreyas535 well, it was my point actually - instead passing index back and forth just push back and then reverse it if necessary...
@zacharyclarke6896
@zacharyclarke6896 2 года назад
would you say that topsort gives you an approximate solution or does it give you an exact solution.
@Shreyas535
@Shreyas535 2 года назад
@@zacharyclarke6896 there might be other solutions possible as well. But all are accurate.
@sarfarazalam6077
@sarfarazalam6077 4 года назад
Man you make difficult topic easy to understand, very nice video. It is very great , how you represent topics in abstract way:)
@pulgupta
@pulgupta 4 года назад
Well structured and well explained tutorials. Thank you.
@MotivationYoucanandyouwi-hg2zt
Thanks a lot for this video, the algoritham is easy to understand because of the animation!
@Kalessin89
@Kalessin89 4 года назад
Your videos are very well produced, thank you very much for the efforts you put into them! Like some other folks have said, I wish Kahn's algorithm was also covered, it is pretty intuitive too and allows for cycle detection.
@WilliamFiset-videos
@WilliamFiset-videos 4 года назад
Thanks for the suggestion Louis, Kahns truly is a really great algorithm. It's especially good for beginners because it's soo simple and intuitive. I'll put together a video if I find the time
@tinfuyiu3940
@tinfuyiu3940 2 года назад
This is a really good tutorial! Thank you for your work!
@GMatos-qg4ec
@GMatos-qg4ec Год назад
Finally a great video! Thanks William
@Anubis10110
@Anubis10110 4 года назад
Thank you so much, so clear and concise. Appreciate it.
@live_mocha
@live_mocha 5 лет назад
This video saved so much time. God bless you pal : ))
@y2k898
@y2k898 2 года назад
The fact you can clearly explain the concept and Algo under 15mins, proves you have mastered this topic and gain deep understanding, kudos.
@ahmadsaeed7168
@ahmadsaeed7168 4 года назад
Your explanation is clear and examples are interesting.
@BATCHFILETUTORIALS
@BATCHFILETUTORIALS Год назад
Wow this tutorial is amazing! Made perfect sense to me!
@user-oe7xl3to3s
@user-oe7xl3to3s Год назад
Thank you, very clear and precise explanation.
@garamburito
@garamburito 3 года назад
It was not clear to me why the sorting process could starts from any node of the graph. I finally found the answear in your animiation. Thanks a lot.
@davidm.johnston8994
@davidm.johnston8994 3 года назад
Thanks a lot William ! This is really helpful.
@gokulkumarbhoomibalan5413
@gokulkumarbhoomibalan5413 3 года назад
Clean, precise, awesome!!
@Udestocome
@Udestocome Месяц назад
Great explanation! Thank you.
@danverzhao9912
@danverzhao9912 3 года назад
Very well explained! Thank you! At this point of my online uni, i'm just skim through the lecture recording and just search up related topic videos on youtube to learn. Why can't the uni just gave us a list of youtube videos to learn.
@harsha4692
@harsha4692 4 года назад
9:17 from the given solution , K is given before I but K does not have a path to I. Is it supposed to happen,can you please tell me?
@NGBigfield
@NGBigfield 4 года назад
Again, Such a great video!
@sanskarsharma9494
@sanskarsharma9494 3 года назад
Thanks for this amazing video !
@sido7740
@sido7740 2 года назад
An application of DAGs is representing circuits as a collection of gates, where subsequent gates require the inputs of previous gates, which is a perfect problem to use topological sorting on as it allows for iterative solutions to circuit propagation!
@devanshmesson2777
@devanshmesson2777 3 года назад
Thank you so much. A clear explanation!!
@chenjason2598
@chenjason2598 Год назад
Clear explanation and nice code!
@prabhakarpalanivel6472
@prabhakarpalanivel6472 5 лет назад
Nicely done, thanks!
@umairalvi7382
@umairalvi7382 3 года назад
The good things is you went from total basics and that's what matters for understanding
@akshitg
@akshitg 5 лет назад
Kudos for explaining the topological sort in simplest way possible 🙂
@harinijeyaraman8789
@harinijeyaraman8789 3 года назад
Loved this !!!! Thaaaaanks a bunch ! Well explained !!
@studytime4048
@studytime4048 3 года назад
In case of a rooted tree, is it sufficient to do the level order traversal to get the topological ordering?
@greaterthanKTWS
@greaterthanKTWS 6 лет назад
Awesome work man.
@raymondyoo5461
@raymondyoo5461 5 лет назад
Wow Thanks so much. Animation helped a lot
@yangwilliam3137
@yangwilliam3137 11 месяцев назад
GREAT, love the animation.
@BreadWinner330
@BreadWinner330 4 года назад
Thanks man, you're the best!
@chinmaygajjardeveloper
@chinmaygajjardeveloper Год назад
Thank you for great explanation!
@evgenirusev818
@evgenirusev818 3 года назад
Awesome video. Thanks!
@reyou7
@reyou7 3 года назад
such a great animation, thanks!
@ra-ph-ael
@ra-ph-ael 4 года назад
This is sooo good!
@Lime-rr6te
@Lime-rr6te 4 года назад
its the best video ever uploaded to you tube. EVER, LIKE FOR EVER. (DABs like a boss) God Damm it feels good to be me.
@Lime-rr6te
@Lime-rr6te 4 года назад
This guy knows how to live life
@rohan8arora
@rohan8arora 4 года назад
thank you. extremely helpful. :D
@oussamaabdelwahed5594
@oussamaabdelwahed5594 3 года назад
GREAT explanation , Thank's
@mtjokro
@mtjokro 3 года назад
Amazing viz, thank you!
@08JuHan
@08JuHan 2 года назад
kudos! thanks a lot for posting
@jingchaozhang408
@jingchaozhang408 4 года назад
10:59 We already has an array V to record the visited node. Why do you define another array visitedNodes?
@rizkimaulana7331
@rizkimaulana7331 8 месяцев назад
THANK YOU SO MUCH
@huuarethey
@huuarethey 3 года назад
thank you william
@XnDxNdXnD
@XnDxNdXnD 5 лет назад
Exellent work
@annazaitseva6213
@annazaitseva6213 2 года назад
Hi! visitedNodes plays a role of a stack, why you iterate it from the first element but not pop last to get order[i]?
@huzaifaaejaz9648
@huzaifaaejaz9648 6 лет назад
Can you also do a video based on Kahn's Algorithm for topological sort, based on inDegrees rather than outDegrees?
@nosh3019
@nosh3019 6 месяцев назад
Thanks!
@nguyenvankhanhduy3958
@nguyenvankhanhduy3958 3 года назад
Great content man.
@japhethobala3753
@japhethobala3753 3 года назад
Thanks a lot.
@shreyashachoudhary480
@shreyashachoudhary480 2 года назад
Concise++!
@JieWei7912
@JieWei7912 2 месяца назад
Thank you.
@gokusaiyan1128
@gokusaiyan1128 2 года назад
what is equivalent of V[edge.to] in python ?
@californiaflying6637
@californiaflying6637 Год назад
Might be good to explain how to use the topo sort result to then actually solve the course scheduling problem (for example).
@kmishy
@kmishy 3 года назад
Lots of hard work sir
@justinmlawrence
@justinmlawrence 2 года назад
So good!
@usman8872
@usman8872 2 года назад
if i have to reach D, the array says , i have to visit K ???
@bouzie8000
@bouzie8000 2 месяца назад
top top explanation
@lautarolavecchia5995
@lautarolavecchia5995 5 лет назад
very useful
@ngbtvezadtht
@ngbtvezadtht 9 дней назад
any reason why you use a list and have to worry about/handle an index, when you could just use a stack? and pop from stack to get the ordering? it seems much easier to do without having to code up extra stuff to handle the index.
@contactdi8426
@contactdi8426 3 месяца назад
Lovely!
@maksimisayenka2058
@maksimisayenka2058 Год назад
great video
@eug_gino
@eug_gino 4 года назад
thanks so much, may I ask, what do you mean by "canonical" example? (1:59)
@SchoolVideosGoHere
@SchoolVideosGoHere 4 года назад
canonical (adj) MATHEMATICS relating to a general rule or standard formula. Basically, it just means this is a very common example throughout computer science, often used when teaching or describing the topic (toposort that is).
@iitianexplains6405
@iitianexplains6405 3 года назад
THANKS
@anthonylee815
@anthonylee815 3 года назад
The tree example is unconnected with your algorithm for TopSort; If the TopSort algorithm is using indegree then the tree example will be really good as an introduction as they are using similar idea. It'd be great if you could always explain the runtime complexity. For this one, why it is O(V+E)?
@sc5shout
@sc5shout 2 года назад
Nice and easy explanation. Love it! I've got one little question, though. Let's take this tree you presents at 4:46 and let's pretend that these nodes are some functions in a program. When A got execute, B, C and D don't depend anymore on anything and could potentially run on separate threads. Let's also say that I know how threads and synchronization primitives work. How to split/detect what nodes can run concurrently? Is there any algorithm for it?
@jasonli1060
@jasonli1060 3 года назад
BEAUTIFUL
@sareek007
@sareek007 2 года назад
Thanks for this awesome video, I have a question. What if when only C and B vertices are remaining and we choose B vertex randomly, will that be correct too? Because choosing B will result in B being added to list and then again selecting C randomly(the only vertex remaining and that will be added at last) Will that be correct?
@trongquocnguyen2786
@trongquocnguyen2786 Год назад
the result is still CB..., i think the key of post order is, let's say we have A and B, if A can lead to B then B would be after A(A...B), but if A can't lead to B, then we have 2 possible results: 1. B lead to A(B...A) 2. B and A don't have anything to do with each other, the relative position of them doesn't matter anymore(that also means A...B, or B...A are both accepted). That's why we can have multiple results.
@jadanabil8044
@jadanabil8044 3 года назад
SSSP finding using topological sort approach, when would I not use this? Seems fastest for the usecase.
@aatifnazar8203
@aatifnazar8203 4 года назад
nice! and neat!
@LightningSpeedtop
@LightningSpeedtop Год назад
Simply beautiful
@edwardhuahui6197
@edwardhuahui6197 5 лет назад
How should i know which node is the starting or randomly choose?
@extremeloco23
@extremeloco23 5 лет назад
Edward Huahui random
@thanhthanhtungnguyen8536
@thanhthanhtungnguyen8536 3 года назад
you are genius
@gabethebabe3840
@gabethebabe3840 6 лет назад
good video!
@IgraphyRupage
@IgraphyRupage 6 лет назад
You rock!
@alicianguyen2625
@alicianguyen2625 Год назад
Why is it important that we only append the value when we're finishing the recursive call, and then reverse it, rather than appending when we mark a node as visited and not needing to reverse the output?
@zss123456789
@zss123456789 4 года назад
Sorry if this is a dumb question... From the animation you said that you could do topological sorting by choosing nodes at random and dfs down their children. But in the code, if I'm reading it correctly, you're just going in the order of the adjacency list. Are there any trade-offs here? Thanks, and great video for a tough topic!
@WilliamFiset-videos
@WilliamFiset-videos 4 года назад
You don't usually know how your DAG is structured/labelled exactly, so beginning at node 0 -> node n-1 is effectively random. You could traverse all the nodes in any permutation and you'll still get a topological sort. To answer your question, I'm not aware of any performance benefits of trying one particular permutation over another.
@zss123456789
@zss123456789 4 года назад
@@WilliamFiset-videos I see, that makes sense, thank you so much!
@ahmedelsabagh6990
@ahmedelsabagh6990 4 года назад
Great
@julianelischer
@julianelischer 5 лет назад
yeah but how do you detect cycles with this method?
@WilliamFiset-videos
@WilliamFiset-videos 5 лет назад
You don't. I mention that the graph must be acyclic and that in order to determine if your graph contains cycles you can use Tarjan's algorithm. Hope this helps!
@anuruddhapremalal
@anuruddhapremalal 4 года назад
@@WilliamFiset-videos Using Tarjan's is an overkill IMO. Here's a good explanation in leetcode to handle cycles with topsort leetcode.com/articles/course-schedule-ii/?page=2
@vishaltk3013
@vishaltk3013 3 года назад
The numerical node values and counters were giving me a hard time understanding the code. So I wrote the same code for a different type of graph data. You don't need to maintain index for ordering array as the graph node data is of string type and we can easily concat them. Here's the code. package com.graph; import com.google.common.collect.Lists; import java.util.*; public class TSortPractice { static class EdgeV2 { String to; String from; public EdgeV2(String from, String to) { this.to = to; this.from = from; } } static int n = 5; static Map graph; static String ordering = " "; static Set visitRegister; public static void main(String[] args) { graph = new HashMap(n); visitRegister = new HashSet(n); graph.put("a", Lists.newArrayList(new EdgeV2("a", "b"), new EdgeV2("a", "c"))); graph.put("b", Lists.newArrayList(new EdgeV2("b", "d"))); graph.put("c", Lists.newArrayList(new EdgeV2("c", "d"))); graph.put("d", Lists.newArrayList(new EdgeV2("d", "e"))); topSort(); System.out.println(ordering); } static boolean notVisited(String node){ return !visitRegister.contains(node); } static void doVisit(String node) { visitRegister.add(node); } static void dfs(String currentNode) { doVisit(currentNode); if(graph.containsKey(currentNode)) { for(EdgeV2 edgeV2: graph.get(currentNode)) { String nextNode = edgeV2.to; if(notVisited(nextNode)) dfs(nextNode); } } ordering = currentNode+" "+ordering; } static void topSort() { Set nodes = graph.keySet(); for(String node: nodes) { if(notVisited(node)) dfs(node); } System.out.println("top sort done"); } }
@conde3915
@conde3915 9 месяцев назад
can you explain it in fortnite terms?
@nursultanmuratov1705
@nursultanmuratov1705 9 месяцев назад
Hi, First of all thank you for your explanation. I find your videos very helpful. But I have a question about the example code of your git repository about topological sort. graph.get(0).add(new Edge(0, 1, 3)); graph.get(0).add(new Edge(0, 2, 2)); graph.get(0).add(new Edge(0, 5, 3)); graph.get(1).add(new Edge(1, 3, 1)); graph.get(1).add(new Edge(1, 2, 6)); graph.get(2).add(new Edge(2, 3, 1)); graph.get(2).add(new Edge(2, 4, 10)); graph.get(3).add(new Edge(3, 4, 5)); graph.get(5).add(new Edge(5, 4, 7)); int[] ordering = topologicalSort(graph, N); // // Prints: [6, 0, 5, 1, 2, 3, 4] System.out.println(java.util.Arrays.toString(ordering)); So my question: if node 6 doesn't have relation with any node in any role, why the program return array : [6, 0, 5, 1, 2, 3, 4]?
@WilliamFiset-videos
@WilliamFiset-videos 8 месяцев назад
Node 6 doesn't have any dependencies, and no other node depends on it, therefore it can be placed anywhere in the topological ordering
@mathuratudu7271
@mathuratudu7271 6 лет назад
suscribed
Далее
Topological Sort | Kahn's Algorithm | Graph Theory
13:32
The hidden beauty of the A* algorithm
19:22
Просмотров 849 тыс.
What is DAG?
5:22
Просмотров 89 тыс.
Depth First Search Algorithm | Graph Theory
10:20
Просмотров 450 тыс.
How Dijkstra's Algorithm Works
8:31
Просмотров 1,3 млн
Dijkstra's Shortest Path Algorithm | Graph Theory
24:47
SHA: Secure Hashing Algorithm - Computerphile
10:21
Просмотров 1,2 млн