Backtracking (Think Like a Programmer)

Поділитися
Вставка
  • Опубліковано 15 січ 2018
  • Backtracking is used when you need to find the correct series of choices that will solve a problem. The example I use here is finding one's way through a maze. You can use the basic idea with or without recursion; if you haven't seen my other videos on recursion, start with the first one at • Recursion (Think Like ...
    This topic was a viewer suggestion--your suggestions for future videos are welcome.
    If you want to read more about my programming concepts, check out my "Think Like a Programmer" book. If you've found that you are able to read programs and understand programming language syntax but aren't always confident writing programs from scratch, my book can help.
    For more information on the book head to one of these:
    Amazon page for the book: amzn.to/1MZlmlY
    My site: www.vantonspraul.com/TLAP
    My publisher's site: nostarch.com/thinklikeaprogrammer
    Connect with me:
    My site: vantonspraul.com
    Twitter: / vantonspraul
    Facebook: / thinklikeaprog
  • Наука та технологія

КОМЕНТАРІ • 108

  • @sharadskywalker
    @sharadskywalker 2 роки тому +67

    "Don't even think about the recursion that's happening. Just imagine you are calling a different, working function" - Best explanation ever. This line lit the lightbulb in my head. Thanks :)

  • @johnnosek731
    @johnnosek731 Місяць тому +2

    dude - this was the video that actually unlocked the concept of backtracking for me, in a way that I can now start to understand problems going forward. Huge props. I will have to check out your library of videos and i'm not sure if you're still making them but if so I'd love to hear you explain some more concepts. Thanks for making the effort, its much appreciated

  • @justins7796
    @justins7796 4 роки тому +49

    This was amazing, thank you for also not jumping into recursion but instead showing this solution.

  • @vantonspraul
    @vantonspraul  6 років тому +64

    Hope everyone is having a great 2018 so far. This video's topic was viewer suggested. If you have an idea for a future video, let me know!

    • @buzzbuddy5655
      @buzzbuddy5655 6 років тому

      Dijkstra and belmanford shortest algorithm ...Can u explain us.practically
      ...

    • @vantonspraul
      @vantonspraul  6 років тому +7

      Sure, that sounds like a good topic. I'll add it to the list. Thanks for the suggestion!

    • @saikumartadi8494
      @saikumartadi8494 6 років тому +2

      sir video tutorials are common nowadays but ur videos are unique because u r speaking about how to approach the problem rather than giving a question and solvng it so do more of such videos on how to approach the problem in a different manner

    • @Jo_Wick
      @Jo_Wick 6 років тому

      Well done on the video!

    • @madhavarampranav4498
      @madhavarampranav4498 4 роки тому

      Can you do it for python please

  • @mojo9188
    @mojo9188 3 роки тому +5

    Thank you so much for creating this video - you explained recursive backtracking in a very easy to understand way, as well as showing the relevant code!

  • @perstarke1295
    @perstarke1295 2 роки тому +8

    "Not think about the backtracking" - this literally changed my life :D So good!

  • @pradpradprad1
    @pradpradprad1 Рік тому

    I was looking for videos on backtracking.. i did not want to waste my time.. so i scrolled many times before i found a video title that talked about "thinking" about backtracking.. well done sir!!

  • @vidpulse4267
    @vidpulse4267 Рік тому

    this is one of the best explanations I've ever seen. I wish you to keep going on to brush up more information

  • @pranavhegde6470
    @pranavhegde6470 2 роки тому +1

    that Robot analogy was amazing!
    Thanks for the video

  • @ethancox6967
    @ethancox6967 2 роки тому +5

    This is one of the best explanations I've ever found. Thanks for making this video :)

    • @vantonspraul
      @vantonspraul  2 роки тому +1

      Thanks for your comment. Glad you found it useful.

  • @snowglider400
    @snowglider400 3 роки тому +1

    You are amazing. You really made backtracking very simple.

  • @avatsavirs
    @avatsavirs 3 роки тому

    Best backtracking video I found on youtube.

  • @marcvashcane8332
    @marcvashcane8332 4 роки тому +3

    Thank you so much! I've learned new things from you.

  • @Tyler-jd3ex
    @Tyler-jd3ex 8 місяців тому

    I haven't finished the video but right now, I keep thinking about all of the different paths that you can go down, keep thinking about the recursion... and then once you return you go up the path until you can make another decision based off of where you end up but it's just very... complex when you think about it... I mean the base cases do make a lot of sense but the way I'm thinking about it right now is too hard to grasp, it's almost mind bending.

  • @RishtonKiBaatein
    @RishtonKiBaatein 2 роки тому

    Thank you very much!! i dont know why you content underrated. keep making videos good luck!

  • @QVL75
    @QVL75 6 років тому

    Very nice explanation! I love it.

  • @agouramhicham
    @agouramhicham 6 років тому +5

    Thank you sir for this wonderful series of videos ...

    • @vantonspraul
      @vantonspraul  6 років тому

      You're welcome! More on the way.

  • @mdmusaddique_cse7458
    @mdmusaddique_cse7458 2 місяці тому

    Splendid explanation!

  • @Albert-lr7ky
    @Albert-lr7ky 2 роки тому

    Thanks man! Very well explained! Keep going!

  • @tagnetorare5401
    @tagnetorare5401 3 роки тому +1

    really inspiring. I always got confused when I tried to think about backtracking in recursions, now I don't.

  • @paulonteri
    @paulonteri 3 роки тому

    This explanation is awesome!

  • @kishanpatel3354
    @kishanpatel3354 2 роки тому

    This channel should create more content. I'm learning a lot.

  • @vishalmishra7018
    @vishalmishra7018 5 років тому +16

    Can you explain 8 queens problem. I found your explanation and reasoning very clear.

  • @ramit8533
    @ramit8533 5 років тому +3

    Thank you for this amazing explanation

  • @Nick-bq1ez
    @Nick-bq1ez 3 роки тому

    Thank you, great video, iterative solution was very intuitive

  • @bryan7300
    @bryan7300 6 років тому +15

    You should be a teacher. The way you lay out your thought process in a simple and detailed manner, allows us to replicate that thought process on our own and gain a deep understanding.

    • @anhminhtran7436
      @anhminhtran7436 5 років тому +7

      He is a teacher :))

    • @michael1
      @michael1 2 роки тому +2

      Yeah, or he could make videos teaching. In a youtube channel or something like that.

    • @Epcgamrman895
      @Epcgamrman895 Рік тому +1

      He is a teacher, and one of the best I’ve had

  • @bsal5347
    @bsal5347 Рік тому +1

    I need some serious help. I can understand how this works but I cant come up with a code by myself.

  • @DHRUVNARAYANSINGH
    @DHRUVNARAYANSINGH 4 роки тому

    Great explanation

  • @BRIGHTENGINEERSACADEMY
    @BRIGHTENGINEERSACADEMY 6 років тому +4

    Best way to understand ...thanks

  • @shubhi4147
    @shubhi4147 4 роки тому

    Really nice explanation! :D

  • @ATeima-kk5ps
    @ATeima-kk5ps 3 роки тому +1

    Amazing explanation. Really helped, thanks so much.

  • @peterfarrell66
    @peterfarrell66 Рік тому

    Was sent here by Sweigart's recursion book!

  • @yousefsahly2067
    @yousefsahly2067 3 роки тому

    wow! just wow! thank you sir!

  • @khadijabarhmi3709
    @khadijabarhmi3709 5 років тому

    thnank you so much the vedio was intersting i would like to use this algorithm to maximize a funtion how can i? thank you in advance

  • @TheSimpleEngineer
    @TheSimpleEngineer 3 роки тому

    Nice vid! What microphone are you using?

  • @jingfenghong2312
    @jingfenghong2312 4 роки тому +1

    it's such an excellent work!

  • @tanhnguyen2025
    @tanhnguyen2025 6 місяців тому

    i have a question. how could u make the while loop with conditions iter and foundoutlet terminates because i didn't see anything to trigger its termination here?

  • @zhichanglin3390
    @zhichanglin3390 Рік тому

    Good idea!

  • @ArthurCousseau
    @ArthurCousseau 10 місяців тому

    Really great video, thanks for giving a non-recursive solution, it helps putting things back in perspective.
    I'm wondering if this can apply to problems that search for a min/max value? For example, the classic "bag" problem which is traditionally solved using more "combinatory-oriented" approaches. (bag can carry at most N kilos and you have many items worth different values and weights, and you want to find the combination of a minimum items that are worth the maximum amount of gold)

    • @vantonspraul
      @vantonspraul  10 місяців тому +1

      Thanks! Yes, you could use recursion to solve that problem, which I know as the knapsack problem. The function could have two parameters: a maximum weight (maxWeight), and a list or other structure with all the items (AllItems), each with a weight and value. Also suppose there is an easy way to make a copy of that list without its first item (AllButFirst). The logic would then be, which of these has greater value?
      A. the recursive call with (maxWeight, AllButFirst)
      B. the recursive call with (maxWeight - weight of first item in AllItems, AllButFirst) + value of the first item in AllItems
      The recursion would stop when AllItems has zero items. Something like that.

  • @jamalparker4487
    @jamalparker4487 10 місяців тому

    Could you show how the list sample_maze is being generated and called in main?
    When I called the backtrack function sample_maze[9] is empty.

  • @Champs3443
    @Champs3443 3 роки тому

    great video!

  • @computersagain
    @computersagain 6 років тому

    Fantastic!

  • @ikjotsingh1723
    @ikjotsingh1723 5 років тому +1

    Can you please do these in java too?

  • @sahmed8961
    @sahmed8961 4 роки тому

    can u give me the link of the code that u showed in video?

  • @mysteriousboi1019
    @mysteriousboi1019 4 роки тому

    Helpful!

  • @serbianbro5322
    @serbianbro5322 3 роки тому

    Nice video!

  • @candaceinkansas
    @candaceinkansas 3 роки тому

    Thanks for the useful example of coding with Stacks.

    • @vantonspraul
      @vantonspraul  3 роки тому

      You are welcome. Thanks for checking it out.

  • @felixxxiam
    @felixxxiam 6 років тому

    Does the code without recursion actually works?? I've tried to replicate it in ruby but I have found some roadblocks. Probably due to the use of List here... How exactly do the begin() and end() methods work?

    • @vantonspraul
      @vantonspraul  6 років тому +3

      The code all works. I've done very little programming in Ruby, so I can't help you there. But I can explain how a list iterator works. Let me start by analogy and see if this helps. Imagine that we declared an array myArray and the constant SIZE specified how many members were in the array. So myArray[0] through myArray[SIZE - 1]. Then begin() would be like setting a variable called arrayPosition to 0, the first index of an array. And end() would give you SIZE, so if arrayPosition == SIZE it means you have advanced arrayPosition off the end of the array. (I think in Ruby you can legally reference elements outside the original range of the array, but you get the idea). Because you can dynamically add elements to arrays in Ruby I think the code should be translatable from C++ lists to Ruby arrays. Let me know if you have any more specific problems and I'll try to help.

  • @Nightaxeblade
    @Nightaxeblade 4 роки тому +1

    Didn't understand how the recursive part worked

  • @jeanniebilliejean
    @jeanniebilliejean 5 років тому

    Amazing 💗

  • @jobinjohn3091
    @jobinjohn3091 3 роки тому

    Nice video. May I also add that he sounds a lot like Kevin Spacey from House of cards...

  • @Jo_Wick
    @Jo_Wick 6 років тому +3

    I have a question... how do you use backtracking in finding all possible permutations of arranging n items?

    • @vantonspraul
      @vantonspraul  6 років тому +5

      That's the kind of problem where "backtracking" would be implicit and hard to see as such. Let's say you wanted to produce all the permutations of the letters A through Z. Let's suppose the language you are working in has a string library with functions or methods that 1) add a character to the end of a string 2) determine the length of a string 3) gets you the character at a certain position and 4) tells you if a character is in a string.
      Then we could write a recursive function to output all permutations of A through Z as follows. Our function has one parameter called PartialPermute. The code in the function would do this:
      -- if PartialPermute has 26 characters, output it and end the function (i.e., return)
      -- otherwise, loop a variable called Letter from 'A' to 'Z'
      ---- inside the loop, check to see if Letter is not already in the string PartialPermute
      ------- if not, copy PartialPermute to TempString, append Letter to TempString, and recursively call this function, passing TempString as the argument
      That's pretty much it. Again, backtracking here is implicit. You could make the backtracking more visible by appending Letter directly to PartialPermutre instead of using TempString, and then you would have to strip the last latter off PartialPermute after the recursive call, a kind of backtracking.
      Of course, if you wanted to store the results instead of display them or make a more general permutation function this would have to be expanded a bit but that's the basic idea.

    • @Jo_Wick
      @Jo_Wick 6 років тому

      Thank you! I have researched a little bit on the subject and your video was the best explanation of even an indirect example of the problem I had. Well done!

  • @yongkailiu1448
    @yongkailiu1448 3 роки тому

    recursion is so counter-intuitive!

  • @fernandoguirao3748
    @fernandoguirao3748 2 роки тому

    very cool

  • @mikeKotlarski
    @mikeKotlarski 5 років тому +3

    What is this typeface? It's very pleasing

    • @AlannaKingrose
      @AlannaKingrose 5 років тому

      Looks like Consolas to me :)

    • @vantonspraul
      @vantonspraul  5 років тому +2

      Sorry for the delay. It's Futura-Book.

  • @kakashi99908
    @kakashi99908 2 роки тому

    If you want to know what is happening with recursive backtracking each possible route (assuming the maze is solvable) is made out after each step you take. The program knows all the results before it actually prints back anything to you! Like a teacher grading a paper, you don't know the grade until they tell you. If you step into a wall the code says welp I am done time to free up some memory and undos the step that led you to the wall. Why? Because programming languages keep track of things (like each step in a maze) using a stack of method calls. Once you walk into the brick wall in the maze the program says okay nothing to do here lets pop off all our steps. Oh wait now I can go this way (0-3)
    Obviously just imagining you are calling a different, working function is a much simpler way to think about it.😅

  • @attilavarkonyi7066
    @attilavarkonyi7066 3 роки тому

    quality content

  • @maciejrogala5928
    @maciejrogala5928 4 роки тому +1

    Whats the difference between this and DFS?

    • @ScribbleDribble
      @ScribbleDribble 2 роки тому

      DFS is an implementation of backtracking for graphs.

  • @LearnYardYT
    @LearnYardYT 6 років тому +4

    Best explanation 😎

    • @vantonspraul
      @vantonspraul  6 років тому

      Thank you! I'm glad you liked it.

  • @paulovictor9963
    @paulovictor9963 6 років тому +1

    I have a doubt,this library that includes "push_back", "empty", "insert", how can i implement in C?
    (don't get angry please, i'm still learning, but in C, not C++)

    • @nicolaswolyniec1354
      @nicolaswolyniec1354 6 років тому

      you need to do by your self. They are not included in standard c libraries.

    • @paulovictor9963
      @paulovictor9963 6 років тому

      Nicolas Wolyniec thanks

  • @itsplaytime8690
    @itsplaytime8690 3 роки тому

    Amazing pls more

  • @vasans7314
    @vasans7314 4 роки тому +2

    #cons : Type your program while you're explaining otherwise it will be difficult to go through. Explain the concept before hand.
    Thanks for your Video👍

  • @beverlyHillsAgent
    @beverlyHillsAgent Рік тому

    The maze problem is basically solved by depth-first search.

  • @johnnybatafljeska6368
    @johnnybatafljeska6368 5 років тому +1

    Nice, but it video is lacking graphical input on what is happening in each step of the backtracking

  • @onemanenclave
    @onemanenclave 10 місяців тому

    this is great but i wish you could explain the same thing on python :(

    • @onemanenclave
      @onemanenclave 10 місяців тому

      would be nice if you used a dark or black background too

  • @atmanirbharladka4467
    @atmanirbharladka4467 5 років тому

    Dude, In the 1st solution you have used the (!) operator with foundOutlet(line 26) which is declared false. Your program will never enter the second loop.
    Remove (!) then the program will work just fine.
    In the first program when I'm printing iter at line 25 and line 27(say) i.e before and after the second while loop its giving me {1,0,1,0,1,0,3,4,3,4} and {1,0,2,1,0,2,1,3,0,4,3,5,4,3,5,7,4,8} respectively. Im unable to understand how the iterator is moving.

    • @markrayne5382
      @markrayne5382 4 роки тому +2

      um no that is wrong, the loop will execute as foundOutlet is set to false, and the second while loop only executes if this boolean value is set to false. if foundOut was set to true then the loop would not execute

  • @heteroerectus
    @heteroerectus 10 місяців тому +2

    An even better approach is just to make all the right decisions the first time around. Then you never have to backtrack.

    • @vantonspraul
      @vantonspraul  10 місяців тому +1

      Ha! For that you'll need a non-deterministic computer. You still don't make only right decisions, but because you make all possible decisions simultaneously, you can pick the one that ends up at the exit.

  • @Jerret17
    @Jerret17 Рік тому

    widce

  • @DuongTran-zh6td
    @DuongTran-zh6td 3 роки тому

    define

  • @elij.9801
    @elij.9801 Рік тому

    where can we get the source code?

  • @nuiben7579
    @nuiben7579 4 місяці тому

    Dear UA-cam Algorithm, please give me more of these practical SWE videos and less tech influencer garbage

    • @vantonspraul
      @vantonspraul  4 місяці тому +1

      Oh, if only we could talk directly to the algorithm...anyway, glad you found it helpful.

  • @Narriz
    @Narriz 2 роки тому

    *Applause*

  • @echol244
    @echol244 3 роки тому

    Could you program when you teach instead of talking about the code which has been done?

  • @smartconjurers2509
    @smartconjurers2509 4 роки тому +1

    U sound like khan academy!

  • @calmyourmind5617
    @calmyourmind5617 2 роки тому

    everyone saying amzing amazing just answer one question why (!foundOutlet) is written in while loop ?

    • @vantonspraul
      @vantonspraul  2 роки тому +1

      I can try to answer that. Do you mean literally why it's part of the while loop condition? That loop exists to set foundOutlet to true if we find a connection from the current point to an unvisited point. We're not counting how many unvisited points we can reach, we only need to know if we can reach one, or not. So once we find an unvisited point (setting foundOutlet to true), we don't need to continue the loop further. That's why the !foundOutlet condition. Of course there would other ways of accomplishing the same thing. Let me know if this isn't what you meant.