Backtracking (Think Like a Programmer)

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

V. Anton Spraul

V. Anton Spraul

6 жыл бұрын

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

Пікірлер: 110
@sharadskywalker
@sharadskywalker 2 жыл бұрын
"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 :)
@justins7796
@justins7796 4 жыл бұрын
This was amazing, thank you for also not jumping into recursion but instead showing this solution.
@vantonspraul
@vantonspraul 6 жыл бұрын
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 жыл бұрын
Sure, that sounds like a good topic. I'll add it to the list. Thanks for the suggestion!
@saikumartadi8494
@saikumartadi8494 6 жыл бұрын
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
@johnnosek731
@johnnosek731 3 ай бұрын
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
@mojo9188
@mojo9188 3 жыл бұрын
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!
@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!!
@perstarke1295
@perstarke1295 3 жыл бұрын
"Not think about the backtracking" - this literally changed my life :D So good!
@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 3 жыл бұрын
that Robot analogy was amazing! Thanks for the video
@snowglider400
@snowglider400 3 жыл бұрын
You are amazing. You really made backtracking very simple.
@marcvashcane8332
@marcvashcane8332 4 жыл бұрын
Thank you so much! I've learned new things from you.
@ethancox6967
@ethancox6967 2 жыл бұрын
This is one of the best explanations I've ever found. Thanks for making this video :)
@vantonspraul
@vantonspraul 2 жыл бұрын
Thanks for your comment. Glad you found it useful.
@avatsavirs
@avatsavirs 4 жыл бұрын
Best backtracking video I found on youtube.
@QVL75
@QVL75 6 жыл бұрын
Very nice explanation! I love it.
@Tyler-jd3ex
@Tyler-jd3ex 10 ай бұрын
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!
@ramit8533
@ramit8533 5 жыл бұрын
Thank you for this amazing explanation
@vishalmishra7018
@vishalmishra7018 5 жыл бұрын
Can you explain 8 queens problem. I found your explanation and reasoning very clear.
@tagnetorare5401
@tagnetorare5401 3 жыл бұрын
really inspiring. I always got confused when I tried to think about backtracking in recursions, now I don't.
@Albert-lr7ky
@Albert-lr7ky 2 жыл бұрын
Thanks man! Very well explained! Keep going!
@agouramhicham
@agouramhicham 6 жыл бұрын
Thank you sir for this wonderful series of videos ...
@vantonspraul
@vantonspraul 6 жыл бұрын
You're welcome! More on the way.
@Nick-bq1ez
@Nick-bq1ez 3 жыл бұрын
Thank you, great video, iterative solution was very intuitive
@kishanpatel3354
@kishanpatel3354 3 жыл бұрын
This channel should create more content. I'm learning a lot.
@paulonteri
@paulonteri 3 жыл бұрын
This explanation is awesome!
@jingfenghong2312
@jingfenghong2312 4 жыл бұрын
it's such an excellent work!
@shubhi4147
@shubhi4147 5 жыл бұрын
Really nice explanation! :D
@bryan7300
@bryan7300 6 жыл бұрын
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 жыл бұрын
He is a teacher :))
@michael1
@michael1 2 жыл бұрын
Yeah, or he could make videos teaching. In a youtube channel or something like that.
@Epcgamrman895
@Epcgamrman895 Жыл бұрын
He is a teacher, and one of the best I’ve had
@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
@mdmusaddique_cse7458
@mdmusaddique_cse7458 4 ай бұрын
Splendid explanation!
@DHRUVNARAYANSINGH
@DHRUVNARAYANSINGH 4 жыл бұрын
Great explanation
@BRIGHTENGINEERSACADEMY
@BRIGHTENGINEERSACADEMY 6 жыл бұрын
Best way to understand ...thanks
@vantonspraul
@vantonspraul 6 жыл бұрын
Thanks! Glad it was helpful.
@yousefsahly2067
@yousefsahly2067 3 жыл бұрын
wow! just wow! thank you sir!
@ikjotsingh1723
@ikjotsingh1723 5 жыл бұрын
Can you please do these in java too?
@ATeima-kk5ps
@ATeima-kk5ps 3 жыл бұрын
Amazing explanation. Really helped, thanks so much.
@TheSimpleEngineer
@TheSimpleEngineer 4 жыл бұрын
Nice vid! What microphone are you using?
@xosomobiofficial
@xosomobiofficial 6 жыл бұрын
video very easy understand.thanks!
@vantonspraul
@vantonspraul 6 жыл бұрын
Glad you liked it!
@peterfarrell66
@peterfarrell66 Жыл бұрын
Was sent here by Sweigart's recursion book!
@Champs3443
@Champs3443 3 жыл бұрын
great video!
@sahmed8961
@sahmed8961 4 жыл бұрын
can u give me the link of the code that u showed in video?
@zhichanglin3390
@zhichanglin3390 Жыл бұрын
Good idea!
@computersagain
@computersagain 6 жыл бұрын
Fantastic!
@bsal5347
@bsal5347 Жыл бұрын
I need some serious help. I can understand how this works but I cant come up with a code by myself.
@saymatasnim5912
@saymatasnim5912 4 күн бұрын
Same here!!!
@serbianbro5322
@serbianbro5322 3 жыл бұрын
Nice video!
@ArthurCousseau
@ArthurCousseau Жыл бұрын
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 Жыл бұрын
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.
@jeanniebilliejean
@jeanniebilliejean 5 жыл бұрын
Amazing 💗
@mysteriousboi1019
@mysteriousboi1019 4 жыл бұрын
Helpful!
@jamalparker4487
@jamalparker4487 Жыл бұрын
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.
@Nightaxeblade
@Nightaxeblade 4 жыл бұрын
Didn't understand how the recursive part worked
@tanhnguyen2025
@tanhnguyen2025 7 ай бұрын
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?
@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 жыл бұрын
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.
@jobinjohn3091
@jobinjohn3091 3 жыл бұрын
Nice video. May I also add that he sounds a lot like Kevin Spacey from House of cards...
@attilavarkonyi7066
@attilavarkonyi7066 3 жыл бұрын
quality content
@Jo_Wick
@Jo_Wick 6 жыл бұрын
I have a question... how do you use backtracking in finding all possible permutations of arranging n items?
@vantonspraul
@vantonspraul 6 жыл бұрын
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!
@fernandoguirao3748
@fernandoguirao3748 2 жыл бұрын
very cool
@mikeKotlarski
@mikeKotlarski 5 жыл бұрын
What is this typeface? It's very pleasing
@AlannaKingrose
@AlannaKingrose 5 жыл бұрын
Looks like Consolas to me :)
@vantonspraul
@vantonspraul 5 жыл бұрын
Sorry for the delay. It's Futura-Book.
@itsplaytime8690
@itsplaytime8690 3 жыл бұрын
Amazing pls more
@LearnYardYT
@LearnYardYT 6 жыл бұрын
Best explanation 😎
@vantonspraul
@vantonspraul 6 жыл бұрын
Thank you! I'm glad you liked it.
@candaceinkansas
@candaceinkansas 4 жыл бұрын
Thanks for the useful example of coding with Stacks.
@vantonspraul
@vantonspraul 4 жыл бұрын
You are welcome. Thanks for checking it out.
@yongkailiu1448
@yongkailiu1448 3 жыл бұрын
recursion is so counter-intuitive!
@maciejrogala5928
@maciejrogala5928 4 жыл бұрын
Whats the difference between this and DFS?
@ScribbleDribble
@ScribbleDribble 3 жыл бұрын
DFS is an implementation of backtracking for graphs.
@paulovictor9963
@paulovictor9963 6 жыл бұрын
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
@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.😅
@vasans7314
@vasans7314 4 жыл бұрын
#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 2 жыл бұрын
The maze problem is basically solved by depth-first search.
@onemanenclave
@onemanenclave Жыл бұрын
this is great but i wish you could explain the same thing on python :(
@onemanenclave
@onemanenclave Жыл бұрын
would be nice if you used a dark or black background too
@DuongTran-zh6td
@DuongTran-zh6td 3 жыл бұрын
define
@johnnybatafljeska6368
@johnnybatafljeska6368 5 жыл бұрын
Nice, but it video is lacking graphical input on what is happening in each step of the backtracking
@Jerret17
@Jerret17 Жыл бұрын
widce
@heteroerectus
@heteroerectus 11 ай бұрын
An even better approach is just to make all the right decisions the first time around. Then you never have to backtrack.
@vantonspraul
@vantonspraul 11 ай бұрын
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.
@elij.9801
@elij.9801 2 жыл бұрын
where can we get the source code?
@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 жыл бұрын
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
@nuiben7579
@nuiben7579 5 ай бұрын
Dear KZfaq Algorithm, please give me more of these practical SWE videos and less tech influencer garbage
@vantonspraul
@vantonspraul 5 ай бұрын
Oh, if only we could talk directly to the algorithm...anyway, glad you found it helpful.
@Narriz
@Narriz 2 жыл бұрын
*Applause*
@smartconjurers2509
@smartconjurers2509 4 жыл бұрын
U sound like khan academy!
@echol244
@echol244 3 жыл бұрын
Could you program when you teach instead of talking about the code which has been done?
@calmyourmind5617
@calmyourmind5617 2 жыл бұрын
everyone saying amzing amazing just answer one question why (!foundOutlet) is written in while loop ?
@vantonspraul
@vantonspraul 2 жыл бұрын
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.
Finding the Best Path (Dijkstra's Algorithm)
17:14
V. Anton Spraul
Рет қаралды 13 М.
Create a Sudoku Solver In Java In 20 Minutes - Full Tutorial
20:25
Coding with John
Рет қаралды 318 М.
39kgのガリガリが踊る絵文字ダンス/39kg boney emoji dance#dance #ダンス #にんげんっていいな
00:16
💀Skeleton Ninja🥷【にんげんっていいなチャンネル】
Рет қаралды 8 МЛН
Double Stacked Pizza @Lionfield @ChefRush
00:33
albert_cancook
Рет қаралды 86 МЛН
마시멜로우로 체감되는 요즘 물가
00:20
진영민yeongmin
Рет қаралды 35 МЛН
Sigma Kid Hair #funny #sigma #comedy
00:33
CRAZY GREAPA
Рет қаралды 35 МЛН
Mastering Dynamic Programming - How to solve any interview problem (Part 1)
19:41
How Dijkstra's Algorithm Works
8:31
Spanning Tree
Рет қаралды 1,3 МЛН
5 Simple Steps for Solving Any Recursive Problem
21:03
Reducible
Рет қаралды 1,2 МЛН
SHA: Secure Hashing Algorithm - Computerphile
10:21
Computerphile
Рет қаралды 1,2 МЛН
Programming Loops vs Recursion - Computerphile
12:32
Computerphile
Рет қаралды 1,5 МЛН
The N Queens Problem using Backtracking/Recursion - Explained
14:29
Back To Back SWE
Рет қаралды 135 М.
Java vs JavaScript
14:54
Codecademy
Рет қаралды 382 М.
Recursion (Think Like a Programmer)
10:42
V. Anton Spraul
Рет қаралды 155 М.
5 Problem Solving Tips for Cracking Coding Interview Questions
19:12
Лазер против камеры смартфона
1:01
Newtonlabs
Рет қаралды 714 М.
Rate This Smartphone Cooler Set-up ⭐
0:10
Shakeuptech
Рет қаралды 4,5 МЛН
iPhone 15 Pro Max vs IPhone Xs Max  troll face speed test
0:33
Сколько реально стоит ПК Величайшего?
0:37
Я купил первый в своей жизни VR! 🤯
1:00
Вэйми
Рет қаралды 2,6 МЛН