Depth First Search (DFS) Explained: Algorithm, Examples, and Code

Sdílet
Vložit
  • čas přidán 31. 05. 2024
  • In this video, I explain the fundamental ideas behind the Depth First Search (DFS) graph algorithm. We first introduce the concept of a graph traversal. We then go through several examples of DFS to provide intuition. Afterwards, we then go through both a recursive and iterative implementation with provided code. We discuss the differences between the implementation and also make a distinction between a preorder and post order DFS traversal. We then finish the video off with some practical and fun applications of depth first search in graph theory.
    0:00 Intro and Preview
    0:50 Graph Traversal
    1:20 DFS Walkthrough and Examples
    6:26 Recursive Implementation
    11:08 Iterative Implementation
    15:06 Preorder vs Postorder DFS
    17:01 DFS Applications
    Support: / reducible
    This video wouldn't be possible without the open source manim library created by 3blue1brown: github.com/3b1b/manim
    Here is link to the repository that contains the code used to generate the animations in this video: github.com/nipunramk/Reducible

Komentáře • 294

  • @hetsmiecht1029
    @hetsmiecht1029 Před 3 lety +751

    This is how I explore caves in Minecraft.

    • @abhishek.rathore
      @abhishek.rathore Před 3 lety +17

      I had the exact same idea. Lol ;)

    • @zuhairmehdee
      @zuhairmehdee Před 3 lety +48

      This is a surprisingly intuitive comparison. Thanks a lot. +

    • @ElektrykFlaaj
      @ElektrykFlaaj Před 3 lety +23

      except caves in minecraft often have no dead end

    • @abhishek.rathore
      @abhishek.rathore Před 3 lety +11

      @@ElektrykFlaaj yeah and they often loop back too

    • @ironlegnebula
      @ironlegnebula Před 3 lety +1

      +1 best system, would recommend

  • @jamesmarx1144
    @jamesmarx1144 Před 3 lety +377

    The thing I love most about great channels using manim, is that i never feel like im watching a 3B1B rip-off, just an intelligent explanation of a topic. Keep up the amazing videos

    • @looksintolasers
      @looksintolasers Před 3 lety +21

      TIL that manim is a thing.

    • @YoTengoUnLCD
      @YoTengoUnLCD Před 3 lety +5

      I feel there are some channels that definitely feel like a rip-off, like vcubingx. It kinda hurts to see a 3b1b-ish thing with lackluster explanations and general quality. This channels pretty good though, and it’s improving noticeably.

    • @williamrutherford553
      @williamrutherford553 Před 2 lety +4

      Eh I don't know, they do feel a bit samey. The way things are shown and animated is pretty consistent, I think the biggest thing differentiating them from being a ripoff is their specific style. For example, 3B1B uses the little Pi characters to add more personality, I think that just shows even if they use manim there are ways to differentiate yourself in other ways.

  • @mikumikuareka
    @mikumikuareka Před 2 lety +41

    By the way, a very interesting point is that you can convert any recursive function into a stack + while len(stack) > 0 loop because basically that's exactly how computers do that on a low level anyway. In some languages it has some advantages, because while function call stack may be limited, a stack as a structure is practically unlimited, and that lets us achieve very deep levels of recursion without stumbling into stack overflow.

    • @thefamousdjx
      @thefamousdjx Před 6 měsíci +3

      Wow thanks this made me dig deeper and understand even better.

  • @ejejej9200
    @ejejej9200 Před 3 lety +122

    This is the best video on this! I love this channel, it is going to become really popular! Thank you! Love the animations. And the design.

    • @Reducible
      @Reducible  Před 3 lety +13

      Thanks for the kind comment!

  • @alex0917lfo
    @alex0917lfo Před 3 lety +95

    The video is great, as always. However, I have a suggestion: maybe at the end of the video, you can ask some graph questions and let us think how to slove, and finally, you can give the java or python code and the step of it. (just like your recursion video because your recursion video is absolutely amazing.)

    • @Reducible
      @Reducible  Před 3 lety +26

      Thank for the feedback, will try to incorporate more problems in future videos.

  • @ferrisstreamsstuff
    @ferrisstreamsstuff Před 2 lety +69

    great video! I'll also point out (as a few others have hinted) that the iterative approach is very important for large graphs. Default stack sizes on modern OS' are still typically quite small, and it's easy to construct pathological graphs which will cause a stack overflow with a recursive DFS implementation. Using an explicit (and heap-allocated) stack as in the iterative approach works around this (until the machine runs out of memory, of course!), and is a crucial reason why this approach is often chosen.

    • @marioivanovivanov4248
      @marioivanovivanov4248 Před rokem

      Hi can u please tell me more about this? For example how is it possibile to construct a "pathological" graph. i'm assuming that a pathological graph is a graph whose nodes are linked in such a way that when the DFS algorithm is called on the graph, it goes into an infinite recursive loop that overflows the stack.

  • @Saurabh1369
    @Saurabh1369 Před 3 lety +15

    i can feel your effort man, the planning, research, animation, music..
    I'm glad i came across this channel.... you gonna get huge success..

  • @irina1nik
    @irina1nik Před 2 lety +2

    Your content is incredibly good. It's not only comprehensive and to the point, but also enjoyable. Thank you for all the effort you are putting in.

  • @hayk.galstyan
    @hayk.galstyan Před 8 měsíci +1

    This was a great video, explaining not only DFS, but both recursive and iterative versions of it, and presenting applications for DFS, all accompanied by illustrations to make it even more clear. Cant thank you enough!

  • @fulgren0965
    @fulgren0965 Před rokem +5

    The presentation of how to use a stack and pop together was really interesting. I always had trouble with while loops, this pattern makes it so apparent when it is best used.

  • @navneet5084
    @navneet5084 Před 3 lety

    The best CS channel to understand graphs hands down! THANK YOU Reducible!! You are just awesome!

  • @haitu8896
    @haitu8896 Před 2 lety +1

    I really love your explanation, it's short, concise, easy to understand, straight to the point. I watched many another's videos, they were lengthy and hard to understand.

  • @conall5434
    @conall5434 Před 3 lety +5

    You deserve so many more subs. This content is so well explained. Fantastic channel!

  • @dorian0623
    @dorian0623 Před 3 lety +6

    Well structured, easy to follow, beautiful graphics, use of video chapters and real world use cases included. What can I expect more? Superb video.

  • @EmadGohari
    @EmadGohari Před 3 lety +3

    I love 3B1B videos and now these are my favorite too. Thanks for all the effort and excellent explanations!

  • @aminforoutan6065
    @aminforoutan6065 Před 3 lety +3

    absolutely the best explanation on DFS that I have encountered.
    Please make more videos on graph theory and algorithms.

  • @StellahRotich
    @StellahRotich Před 2 lety +2

    Thank you for making DFS and BFS understandable. Simple and on point

  • @zamoqi
    @zamoqi Před 2 měsíci

    Your videos make the difficult concepts so easy to grasp!

  • @henrythai2020
    @henrythai2020 Před 2 lety +2

    This is the best way to explain recursive functions to newbies like me. Thank you so much for such great contents.

  • @montehatch
    @montehatch Před 2 lety +1

    These videos are gold. They go into much more depth than their peers, with expanded intuition, alternatives, and application. Well done sir! P.S. the animation is also top notch.

  • @hanshima_
    @hanshima_ Před 2 lety +6

    One thing that I love about this channel is that, because the quality is so huge, all the comments will start praising the video but also adding new information and providing constructive feedback. I think that people feel compelled to give some retribution after watching such a great video for free.

  • @raunakmitra7868
    @raunakmitra7868 Před 2 lety +13

    2:22 is an example of the classic Cycle Detection algorithm where DFS is used to detect any cycle in a graph G. Child node 2 has a "back-edge" that connects it with the root node 0. This is basically a cycle in the graph.

  • @sdk-yourfriend1561
    @sdk-yourfriend1561 Před rokem +2

    Great video, great teaching, and great animation used here to make things understandable by going into a deeper level of abstraction of all the steps and processes. Before this video, I watched 4-5 videos on DFS that appeared on top after searching and had more views (even in millions) but couldn't understand them clearly. After all, this is the ultimate video that quenched my thirst. Thank you sir for your great content. This channel should grow more and more fast.

  • @hemantmangwani7172
    @hemantmangwani7172 Před 3 lety +11

    Great Content Man and that Recursion video is Awsome . Keep Making more videos.

  • @TheAmberZhang
    @TheAmberZhang Před rokem

    Best video so far I found on DFS algorithm. Very clear explanation. Thank you very much!

  • @shahidahmads
    @shahidahmads Před 3 lety

    probably the best explanation of DFS I have ever come across! thank you! :)

  • @MD.MamunUrRashidHridoy
    @MD.MamunUrRashidHridoy Před měsícem

    The way we designed the animation and the calmness of your voice in the time of explanation and the depth of your discussion just blow my mind. May Almighty Bless You💝

  • @yuriymelnykov1464
    @yuriymelnykov1464 Před 3 lety

    Thank you for the amazing video. This is the most understandable explanation I've ever seen. Visualization, narration and music is very good:)

  • @nadiakruger4206
    @nadiakruger4206 Před 2 lety

    So happy I found this channel and this video! It was really, really helpful.

  • @vaibhavsomani2690
    @vaibhavsomani2690 Před 2 lety

    Thanks for that soft music in background, really helped boosting focus while watching this video. Great explanation as well. Thank you.

  • @aakankshaagrawal223
    @aakankshaagrawal223 Před 3 lety

    JUST WAITING FOR THIS WONDERFUL WONDERFUL GEM OF A CHANNEL TO EXPLODE.
    THANKYOU THIS IS AMZING

  • @tanvitanvi4235
    @tanvitanvi4235 Před 3 lety

    This is the first time I'm posting a comment for a video, simply because I don't really bother to. But this is something. This is that good!
    Sooooo good! Concise and yet complete. Simply brilliant!

  • @Latesttechs
    @Latesttechs Před 3 lety +1

    Amazing video I have already done my bachelors in CS and have seen various videos explaining various Algos but your approach is simple, intuitive and precise among all others please keep it up!

  • @vibhor3049
    @vibhor3049 Před 3 lety

    Brilliant video. Those animations really helped to understand the whole process. Thanks!

  • @redtree732
    @redtree732 Před 6 měsíci

    Okay, I'm 5 minutes in but I had to comment. This is, hands down, the best explanation of DFS I've ever encountered. Thank you so much for this phenomenal video - I hope you keep it up!

  • @kensword
    @kensword Před 3 lety +5

    looking forward to BFS too! Thank you for posting!

  • @wolfy_pride
    @wolfy_pride Před 8 měsíci

    Amazing!!! Please do this for all concepts of DSA. You are a rare gem!!!

  • @abanerjee3704
    @abanerjee3704 Před 2 lety

    I couldn't help myself but comment how beautifully the content has been delivered..... Kudos to u guys, love and appreciation from India🤘🤘

  • @nerodant85
    @nerodant85 Před rokem

    I really love your format, great work, subbed right away

  • @nicholasziglio
    @nicholasziglio Před 2 lety +1

    Brilliantly explained, so simple and clear. You gained a new subscriber!

  • @ishankhan3912
    @ishankhan3912 Před 29 dny

    The best explanation!!This guy is a gem

  • @anbesivamkamal
    @anbesivamkamal Před 3 lety +2

    Simple and Clear:) Thanks for the amazing videos!

  • @vijaykumarreddyalavala3713
    @vijaykumarreddyalavala3713 Před 3 lety +18

    I'm proud for being among the first 1000 subs while I know this channel will explode subs count to millions very soon

    • @ejejej9200
      @ejejej9200 Před 3 lety

      Me too! This channel is going to be huge!

    • @curbyourshi1056
      @curbyourshi1056 Před 3 lety

      It's absolutely happening. Pleased to be part of the blow up.

  • @waseemballoul5604
    @waseemballoul5604 Před 2 lety

    Finally I found the best channel
    That's amazing
    I wish to support you more ...

  • @codewithsimran9899
    @codewithsimran9899 Před 2 lety

    This is Gold! Just one video and I think I'm done understanding graphs. Thanks a lot!

  • @moosegoose1282
    @moosegoose1282 Před 2 lety

    this is probably the best explaination ive came across

  • @shwetamishra3591
    @shwetamishra3591 Před 3 lety +2

    It's really amazing...
    your contents and way of explanation everything is awesome...
    keep it up...

  • @goldenlin9528
    @goldenlin9528 Před 2 lety

    great animations, video, and i love the last part where u mentioned the applications

  • @flamess007
    @flamess007 Před 2 lety

    I really love how you explain and the music, I really love this yt channel thank you so much

  • @ferroumsamir6531
    @ferroumsamir6531 Před rokem

    you do great job. you deserve more appreciation, and you will have it.

  • @yeah5037
    @yeah5037 Před rokem +1

    Loved your amazing explanation, thank you!

  • @xsYlarx1
    @xsYlarx1 Před 3 lety

    Best video ever. Helped me understand the DFS better.

  • @elifsuates4151
    @elifsuates4151 Před rokem

    Perfect explanation. It is may 5th video and just understood everything thanks to you. Great.

  • @migzleon4047
    @migzleon4047 Před 2 lety

    The king of the hill is here... can't wait to become a patreon this content is 🔥...

  • @peterpete5214
    @peterpete5214 Před rokem

    Thank you for the clear explanation very easy to follow. You got a new subscriber keep up the good content👍

  • @jrub3314
    @jrub3314 Před 3 lety

    You get a new suscriber! Amazing videos and explanations! Really really very good!

  • @KodySimpson
    @KodySimpson Před 2 lety

    This is the best video ive ever seen in my life

  • @dreamArmy34
    @dreamArmy34 Před rokem

    I love ur channel 🥺 such a wonderful explanation

  • @priyankareddy7408
    @priyankareddy7408 Před 3 lety

    thank you so much for the amazing explanation and such great animations!

  • @sher.5027
    @sher.5027 Před rokem

    I liked and subscribed. awesome explanation. Good visualization and best animation. Keep the good work.

  • @bivashchakraborty6518
    @bivashchakraborty6518 Před 2 lety

    Thank you so much!!! Much love from India.

  • @ravitiwari1686
    @ravitiwari1686 Před 2 lety

    Great Effort there! Appreciate the time you took to fork Manim and manage it so well for all of us. Regarding the algo in preview, at 8:20, where you mention to maintain boolean values of marked nodes, it should be of size/length - G.order() rather G.size(). For a graph, order = number of vertices = |V| while size = number of edges = |E|. This could cause problems if we have a straight line graph with n nodes connected by (n-1) edges!

  • @nitinkulkarni7942
    @nitinkulkarni7942 Před 3 lety

    This is simply an amazing explanation

  • @oscareriksson9414
    @oscareriksson9414 Před 2 lety

    Really good explaination!

  • @milind-9683
    @milind-9683 Před rokem

    Awesome as always!

  • @Aughadi
    @Aughadi Před rokem

    Best Explained !!!!!
    Thanks from India 🇮🇳!!!!!

  • @makhdoom65
    @makhdoom65 Před rokem

    Amazing explanation. My teacher did the same but you explained it way more easier.

  • @tejasnakhate
    @tejasnakhate Před 3 lety

    I wish this videos came earlier.....great content man!

  • @crunchy3501
    @crunchy3501 Před 2 lety

    You're the man! Perfect explanation!

  • @Yang2j7
    @Yang2j7 Před 2 lety

    Literally just learned about this in class today and it popped up in my recommendation. CZcams algorithm is getting insane.

  • @davidkulman2291
    @davidkulman2291 Před 5 měsíci

    Incredible video!

  • @m.pashakhoshkebari2045

    So well done! Great job

  • @avinashmbhat4256
    @avinashmbhat4256 Před 10 měsíci +1

    Really amazing video 🙌🙌

  • @sahandsanaei555
    @sahandsanaei555 Před rokem

    superb explanation!

  • @IELTS_with_Sahar
    @IELTS_with_Sahar Před rokem

    The mooooost perfect tutorial video eveeeer

  • @bhiep3185
    @bhiep3185 Před 3 lety

    Your channel is amazing! How you don't have hundreds of thousands of subscribers is beyond me. Please keep up the good work!

    • @Reducible
      @Reducible  Před 3 lety +1

      Thank you! Hopefully we get there in the future :)

    • @sivsivsree
      @sivsivsree Před 3 lety

      @@Reducible you will

  • @TomBenBel
    @TomBenBel Před 3 lety +6

    Beautifully animated video, though forgive me if I don't like this way of introducing DFS.
    The main problem is that most of the applications could just as well be solved without DFS:
    Cycle Detection: DFS does not give you all cycles in the way you described, and just determining whether a graph contains cycles can be done by BFS or similar also.
    Finding Connected Components: Any Traversal technique will do nicely.
    Topological Sort: Take Kahn's algorithm. The idea there is your reasoning at 18:37, but translated more directly into an algorithm.
    Maze: There are several ways to create a maze, but granted this one is elegant :)
    This sometimes leaves students wondering whether DFS is just a bad alternative to BFS for the path finding problem. It is not!
    Of course some applications are harder to explain in a video, but here is a surprisingly useful application somewhat related to your examples:
    Partitioning a directed graph into strongly connected components (SCCs, Sets of nodes where you can reach every node from every other node).
    This is useful in e.g. model checking, where you want to proove the correctness of a program, which can be reduces to finding an SCC with a special marking and a loop.
    Checking whether an SCC has a loop and is marked is usually trivial (loop at least two nodes in the SCC or a reflective edge).
    Or you might want to replace SCCs with single nodes, yielding a DAG. This e.g. extends many planning algorithms to handle circular dependencies (exactly the SCCs with several nodes).
    Basic idea without any proofs:
    Every SCC is represented by the node within it first encountered during DFS.
    Start by assuming every node is its own SCC and start the DFS.
    If you keep a hashset of all the nodes currently on the stack (or mark nodes as on the stack), you can efficiently determine whether a node was encountered twice along a path.
    If that happens, you found a loop and can merge all SCCs on the stack from the first encounter to the second.
    An SCC is guaranteed to no longer grow once DFS leaves it (through the node representing it, which you can detect).
    At that point, note the SCC down.
    Side node: Like in your example, the SCCs outputted this way are topologically sorted.
    Sadly, most students never get to learn these more useful applications of DFS, but hey, thats why I'm writing long comments :)
    Thanks for reading!

    • @ron3799
      @ron3799 Před 2 lety +2

      wait, this is really useful info. thank you for taking the time to write this all !

  • @Oscar-vs5yw
    @Oscar-vs5yw Před rokem

    This seems like a very useful algorithm to know, I feel like I can already see some applications of it

  • @inishkohli273
    @inishkohli273 Před 5 měsíci

    I rarely comment on CZcams but I must say you are the exact version of CZcamsr and tutor I am dreaming to be..Before reading the solution and algorithm, we must understand why it was created , what was the intuition behind it... and second thing I loved is bg music..

  • @mohamedmoumni8916
    @mohamedmoumni8916 Před 2 lety

    Thanks for great explanation.

  • @Cassandra81552
    @Cassandra81552 Před 3 lety

    Brilliant. Nice explanation. Really helpful 👌👏👍

  • @alessandroporfirio1910

    Very good explanation, thank you!

  • @geges2395
    @geges2395 Před 3 lety +1

    slick video and great explanation

  • @AlessandroBottoni
    @AlessandroBottoni Před 3 lety

    Fantastic video! Kudos!

  • @jenso413
    @jenso413 Před rokem

    wow, what a great explanation! thank you!

  • @JamesBrodski
    @JamesBrodski Před 2 lety

    Great video! Thank you so much for it.

  • @DEEPAKKUMAR-wk5pk
    @DEEPAKKUMAR-wk5pk Před 2 lety +1

    great explaining video for Graph Thnaks

  • @hasanshovon3402
    @hasanshovon3402 Před 3 měsíci

    best video of DFS for sure

  • @mahdivakili7353
    @mahdivakili7353 Před 3 lety

    Perfectly done. Thanks

  • @vaibhavgaur261
    @vaibhavgaur261 Před rokem

    good animation easy explanation covered a variety of algos in just 20 min. 👍👍👍

  • @vojtaliska1430
    @vojtaliska1430 Před 2 měsíci

    Thank you, I managed to implement this very easily. I am not a programmer and my itterative approach could only handle branches and cycles.

  • @psychedeliccoffee2737

    Great video!

  • @Cruizzerr
    @Cruizzerr Před 2 lety

    great explanation, thanks.

  • @koberowland9798
    @koberowland9798 Před 2 lety

    Awesome video you are a amazing teacher

  • @user-wc1sm8cj8s
    @user-wc1sm8cj8s Před 3 lety

    *Great Content!!!*
    Understood a lot

  • @leozheng370
    @leozheng370 Před 2 lety

    I guess It takes a lot of efforts to make this video. Well done! The details are handled well. e.g. same nodes added to the stack multiple times but only processed once due to the visited check. It is better than the solution in CLRS

  • @crjacinro
    @crjacinro Před 2 lety

    why this video only has 49k views? THIS CONTENT IS AMAZING!

  • @marcusbluestone2822
    @marcusbluestone2822 Před 2 lety +1

    Brilliant, thank you!

  • @rapidlapse
    @rapidlapse Před rokem

    Learnt 2 neat things about Graph algo from this video:
    - Reverse of DFS post-order is the same as topologically sorted graph
    - DFS can be used to generate maze. I always thought some dude spent hours to design mazes in the print newspapers. You are telling me it was just a DFS 😂

  • @expansivegymnast1020
    @expansivegymnast1020 Před 3 lety

    Amazing video!