G-41. Bellman Ford Algorithm

Поделиться
HTML-код
  • Опубликовано: 29 янв 2025

Комментарии • 374

  • @takeUforward
    @takeUforward  2 года назад +102

    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

  • @mandarbhatye17
    @mandarbhatye17 2 года назад +60

    Thanks

  • @harleenkaur7751
    @harleenkaur7751 2 года назад +102

    Thanks Striver. Trust me, even in my paid course, they just simply explained the working of Dijkstra and Bellman without going into such detail. U r the best teacher.

    • @dharmvir2330
      @dharmvir2330 Год назад +9

      True , i am also here from a paid course , Someone believes it or not These explanations are way better than in a paid course.

    • @harshitrautela6585
      @harshitrautela6585 6 месяцев назад +1

      @@dharmvir2330 So why did you take the paid course? Is there any advantage you can think of that the paid course is giving better than Striver(just curious to know)?

  • @EliasEH89
    @EliasEH89 11 месяцев назад +26

    Thank u.
    Note: The Dijkstra's algorithm implemented in G-32 can handle any negative edges graph EXCEPT the following cases:
    1- Directed graph having any negative cycle (cycle with sum < 0)
    2- Undirected graph having any negative edge because the edge in undirected graph is by itself a cycle

    • @Mercer80
      @Mercer80 10 месяцев назад +1

      What if graph is disconnected and negative cycle isnt reachable from source then your first point is false.

    • @shravani2922
      @shravani2922 8 месяцев назад +1

      Your thought is right, my doubt is why not follow Dijkstras algorithm implemented in G-32 for directed graphs with no negative cycles. The time complexity is even less than Bellmanford algorithm. What is the use of Bellman ford algorithm?

    • @tasneemayham974
      @tasneemayham974 8 месяцев назад

      @@Mercer80 I think we can apply a quick visited check? Like we did in the first lectures?

  • @mashfy6314
    @mashfy6314 2 года назад +271

    This guy got superpower. Can be cast as a Marvel hero "The Explainer" .

    • @samarthagarwal6965
      @samarthagarwal6965 2 года назад +23

      And we all guys as watchers 😂

    • @noobcoder6306
      @noobcoder6306 2 года назад +1

      nice one

    • @noobcoder6306
      @noobcoder6306 2 года назад +3

      @@samarthagarwal6965 already taken by the "Watcher"

    • @blutoo1363
      @blutoo1363 Год назад +9

      I think Striver is already a good enough superhero name

    • @amanasrani6405
      @amanasrani6405 7 месяцев назад

      Wahi yr his teachings skills with so much of patiencee

  • @akshaysoni3496
    @akshaysoni3496 Год назад +73

    Improve Time Complexity by exponential with just minor observation:
    Put int count =0; After the first loop & increment the value of count by 1 when the dist array will get updated and at the end of the second loop, if the value of count is not increased then directly return dist array. if no update in dist array happened that means we already calculate dist array, no need to do further iteration, In the worst case it does not have any impact, but for rest, it decreases TC a lot. It Reduce the number of iteration in Best & Average cases.

    • @srimanproductions8396
      @srimanproductions8396 Год назад +1

      this should be pinned

    • @amalkumar256
      @amalkumar256 Год назад

      I did the same thing.

    • @shivangisehgal
      @shivangisehgal Год назад

      exactly!

    • @nalingoyal881
      @nalingoyal881 11 месяцев назад +1

      Is this case even possible? in a graph like this : a-> b-> c . if we have found smaller distance for a->b , we will surely find shorter distance for b->c in next iteration. Let me know if you think differently.

    • @dank7044
      @dank7044 7 месяцев назад +1

      @@nalingoyal881 Bhai you would find smoller distance for c in the same iteration.

  • @av21015
    @av21015 2 года назад +11

    You explained it really well, If I was to trace this myself I would have sat for an entire day.

  • @srinayclg390
    @srinayclg390 2 года назад +30

    when u said "yes u r correct", my confidence became infinity❤

  • @satyakidas7536
    @satyakidas7536 Месяц назад

    After many years I finally understood with your example why bellman ford runs for (n - 1) iterations. Thank you

  • @tanyacharanpahadi158
    @tanyacharanpahadi158 8 месяцев назад +4

    OMG! too much hype about bellman ford algorithm and this is what it is? WOW! you made it so simple. Thanks a ton striver!

  • @naitikrathore3317
    @naitikrathore3317 2 года назад +7

    2 din baad DAA ki paper hai and Bellman Ford aayega exam me, soch hi rha tha ki striver agr next video yhi upload kr de fir to mjaa hi aa jaye and aaj subh dekha BOOM!!

  • @LokeshSharma-hm5jz
    @LokeshSharma-hm5jz Год назад +1

    understood, I dont know why i was afraid of this algo in explaining. You made it a butter.

  • @imajt5
    @imajt5 Год назад +1

    Have watched multiple videos, but got the understanding from this explaination. Thanks

  • @GauravThinks
    @GauravThinks Год назад +14

    Question: why do we need N-1 iterations?
    Reason: Because we first of all set the source distance out ot all the N edges, now we have N-1 edges, to fill their distances w.r.t source, we need at max N-1 iterations for each Node.

  • @arnabdebnath2425
    @arnabdebnath2425 2 года назад +2

    Bhaiya nind se uth ke breakfast mai apka video khaneka Maza hi kuch Alag h…….
    Thank you so much bhaiya ….❤

  • @decepticonWave
    @decepticonWave Год назад +4

    The fact that you explained N-1 is why you are the GOAT. Please make a paid course and we will pay

    • @ashutoshpandey1639
      @ashutoshpandey1639 Год назад

      But the one thing should also be mentioned that if a graph on N nodes have cycle then their is path exist having edges more than N - 1.

  • @rethickpavan4264
    @rethickpavan4264 22 дня назад +1

    point 1: see not all paths will updated till last , its based on the order , so ATMOST (N-1)
    point 2 : no matter how many edges in the graph all will be updated for sure
    hope this finds helpful

  • @ashutoshkumargiri3194
    @ashutoshkumargiri3194 Год назад

    One of the best playlist of Graph on youtube bhaia you deserve more

  • @HarshnitePrasad
    @HarshnitePrasad Год назад +1

    Things i figured out :
    1. If you know a path to reach a node you can figure out the paths to reach nodes adjacent to it.
    2. why repeat n-1 times, every time you run through the edges you find a path to reach the node and the cost to reach it, if its better you update, incase the cost doesnt update you have been able to exhaust the minimum cost path.

  • @jagannathan1014
    @jagannathan1014 Год назад +2

    Shortly, if N nodes, the node at the farthest level will be at

  • @tasneemayham974
    @tasneemayham974 8 месяцев назад +1

    SUBSCRIBED FROM FIRST RECURSION LIST VIDEO, SIRE!!!! UNDERRRSSTOOODDDD

  • @dhanashreegodase4445
    @dhanashreegodase4445 Год назад +1

    thanks striver, you are the real gem

  • @yashshukla1637
    @yashshukla1637 Месяц назад

    AWESOME!!! Bellman Ford will also handle -ve weights + detect -ve Cycles.

  • @Curiousdev01
    @Curiousdev01 Год назад +5

    Amazing content sir !! ..... if I get a job will be because of you.🙂

  • @ashutoshpandey1639
    @ashutoshpandey1639 Год назад +2

    one thing should also be mentioned that if a graph on N nodes have cycle, then their is path exist having more than N - 1 edges from first to last node.
    By the way best explanation on RUclips👌

  • @prateekshrivastava2802
    @prateekshrivastava2802 Год назад

    Best explaination of this algo till date !!

  • @stith_pragya
    @stith_pragya Год назад +2

    Thank You So Much for this wonderful video...........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻

  • @pranshu_awasthi
    @pranshu_awasthi 9 месяцев назад +3

    Dijsktra's code which striver has taught works for negative edges , it just not works for Negative edge cycles. So all in all , it would work for DAG with positive / negative weights.

    • @tasneemayham974
      @tasneemayham974 8 месяцев назад +1

      Of course, because Dijkstra doesn't work for negative edges in UNdirected grapsh: What if you have 0 - 1 with -1 weight? It will give TLE. But in directed, 0->1 with -1, 1 can never go back to 0 so the loop will not work.

    • @pranshu_awasthi
      @pranshu_awasthi 7 месяцев назад +1

      @@tasneemayham974 That's what I said. It works for DAG.

  • @newsbuster2194
    @newsbuster2194 Год назад +1

    Thanks for putting such kind of effort for us.

  • @Kokowangmini
    @Kokowangmini Год назад +1

    understood, It was so Awesome.

  • @alessandrocamilleri1239
    @alessandrocamilleri1239 2 года назад +1

    Top notch explanation as usual. I would have included an update flag to pre-empt unnecessary iterations.

  • @harshith4549
    @harshith4549 7 месяцев назад

    We can also fit the negetive cycle check in the for loop with extending its range to V and checking if its the Vth iteration in relaxtion without writing repeated code. Also the best and worst cases can be improved by keeping a count of how many relaxations done in each iteration which signifies that if at any point no relaxation can be done then no further iteration is required bcoz there will be no change in distances further. Here's how its done:
    vector bellman_ford(int V, vector& edges, int S) {
    vector dist(V, 1e8);
    dist[S] = 0;
    for(int i = 1; i

  • @keshavprasad1017
    @keshavprasad1017 8 месяцев назад

    thank you so much for the clean and crisp explanation.

  • @Chirayu19
    @Chirayu19 Год назад

    You got so much energy, bro!

  • @coder6109
    @coder6109 9 месяцев назад

    Imp when to apply - > when have -ve cycles, idea-> relax all the edges v-1 times , tc->(O(VE))

  • @AyushiPanday12
    @AyushiPanday12 Год назад

    Thanks Striver for these wonderful lectures. Understood.

  • @cinime
    @cinime 2 года назад +1

    Understood! Super amazing explanation as always, thank you very much!!

  • @ayushsharma-bw5ch
    @ayushsharma-bw5ch 2 года назад +1

    we need to relax each edge for n - 1 times but in the code we are running loop for

    • @vishnubanjara5209
      @vishnubanjara5209 2 года назад +6

      if we assume it 0 index based then V-2 is right and if we take it 1 based than simply run it for 1 less as V-1

    • @shreyanshagrawal3115
      @shreyanshagrawal3115 Год назад +3

      for(int i = 0; i < N; i++) : runs for N times ( 0 to N-1)
      for(int i = 0; i < N-1; i++) : runs for N-1 times ( 0 to N-2) - which is required

  • @amankush2408
    @amankush2408 7 месяцев назад

    Understood. Great explanation for the intuition.

  • @CodeMode9313
    @CodeMode9313 Год назад

    Habibi ye ek number bideo bana di tumne toh ...baut baut danyawaad

  • @virgarg9653
    @virgarg9653 Год назад

    Beautiful Explanation . Loved your content keep going 100%

  • @maou_raizen
    @maou_raizen 2 года назад

    the thought process is insane

  • @Kparkhade
    @Kparkhade 6 месяцев назад

    Maja aa gaya
    Itna khatarnak explanation bro 🎉

  • @user-zn3be9ik1x
    @user-zn3be9ik1x 2 года назад

    start the relaxation loop from i=1 to i

  • @Stickman-rz9nu
    @Stickman-rz9nu 8 месяцев назад

    bhaiya , in the for loop terminating condition should be “ i < V “ for n-1 iterations

  • @sdfg204
    @sdfg204 10 месяцев назад

    Had no idea it was this easy, damn. Obviously now that i know the logic, i don't even need to remember it.

  • @suyashjain3223
    @suyashjain3223 Год назад

    Amazing Explanation!!🔥🔥

  • @varunakrishnani7688
    @varunakrishnani7688 2 года назад +1

    Understood!! :)
    Thank you! 🙏🏻😊

  • @rithikraj4316
    @rithikraj4316 6 месяцев назад

    Simple in every cycle worst can be 1 updation, so we need to update n - 1 updation as we already have 0 or src updated manually

  • @ajitpal0821
    @ajitpal0821 2 года назад +1

    5 nodes not edges at 17:24 @take U forward

  • @ankitpandey7262
    @ankitpandey7262 2 года назад

    Understood !! Amazing as always

  • @vidyarthi3944
    @vidyarthi3944 Год назад

    intution was just 🔥🔥🔥🔥🔥🔥🔥🔥

  • @herculean6748
    @herculean6748 2 года назад

    lots of love and respect🙌

  • @CodeNow-nc4rk
    @CodeNow-nc4rk 4 месяца назад

    23:34 -
    If someone is wondering like me as to why the edges are passed by reference using &
    If you don't use a reference, the function would create a copy of the edges vector every time the function is called, which can be very costly in terms of memory and time, especially for large graphs

  • @komalkrishna7836
    @komalkrishna7836 2 года назад

    Wow! very well explained, completely Understood

  • @kaichang8186
    @kaichang8186 4 месяца назад

    understood, thanks for the intuition part

  • @divyareddy7622
    @divyareddy7622 3 месяца назад +1

    takeaway: having n-1 iterations, helps bellman ford to avoid infinite loop. It won't again try to find a better distance.

  • @Alwaysalearner123
    @Alwaysalearner123 Год назад

    In for loop i

  • @aryashjain7893
    @aryashjain7893 2 года назад

    watching it at 4 a.m. and when u say , I got a better guy, it really hurts :)🤣🤣

  • @rajatjakhar3146
    @rajatjakhar3146 2 года назад +1

    great explanation 🔥🔥🔥🔥

  • @vakhariyajay2224
    @vakhariyajay2224 2 года назад +1

    Thank you very much. You are a genius.

  • @shivisingh9975
    @shivisingh9975 Месяц назад

    Understood sir ! thank you so much

  • @kirankuyate6056
    @kirankuyate6056 Год назад

    greate explaination and with great energy while explaining that make people more creative affracting getting more..💖

  • @g51661
    @g51661 Год назад

    Thank you, Striver!
    Understood

  • @harishnaik8164
    @harishnaik8164 Год назад +1

    why adjacent list is not created? why iterate through edges list?

  • @kr_ankit123
    @kr_ankit123 2 года назад +1

    Understood👍👍
    Thanks a lot

  • @soninirav
    @soninirav 2 года назад

    Amazing , very well explained 🔥🔥

  • @sallaklamhayyen9876
    @sallaklamhayyen9876 8 месяцев назад

    great explanation thank you so much and please continue😘😍

  • @smile8510
    @smile8510 2 года назад +2

    Master piece !

  • @doingsneakypeakylike
    @doingsneakypeakylike 2 года назад

    Solid explanation man! Thanks!

  • @kiranpoojary493
    @kiranpoojary493 3 месяца назад

    20:11 activated SUPER SONIC MODE 🔥

  • @amodyadav7523
    @amodyadav7523 День назад

    can I make their weights stored in long long int.... by that I can increse every weight bu a value of INT_MAX...then by dijkstra's algo.. i will return final answer minus INT_MAX..... is this one of the way?

  • @udaytewary3809
    @udaytewary3809 Год назад

    Understood bhaiya 🙏❤️

  • @kasamadhu3509
    @kasamadhu3509 2 года назад +2

    striver: Directed Acyclic Graph with negative edges we can use Dijkstra's right?
    Example: vertices 3, edge 3
    node node weight;
    0 1 10
    1 2 -8
    0 2 5
    source 0 ;
    it is giving 0, 10, 2 correct, bellman ford is used for only detecting negative cycles that can't be done using dijkstra's as you explained in series.

    • @akashkumarsingh8369
      @akashkumarsingh8369 2 года назад +1

      same confusion hai bhai. smjh nhi aa rha agar cycle nhi hua aur negative weight hai to dijkstra glt ans dega ya shi. Dry run krne pr shi hi aa rha hai.

    • @lakshsinghania
      @lakshsinghania Год назад

      @@akashkumarsingh8369 it shouldn't work as per the real meaning of dijkstra's whether its
      1. having neg weights
      2. having neg cycle becoz this already includes negative weight in the path

    • @lakshsinghania
      @lakshsinghania Год назад

      @@akashkumarsingh8369 koi aur tc lo and then check

    • @dhruvgupta3879
      @dhruvgupta3879 Год назад

      it won't work with dijkstra. We mark a node as visited in dijkstra and do not visit it again, which should not be done in case of negative weights.

    • @jiyabhagat6510
      @jiyabhagat6510 Год назад +1

      Yes, Dijkstra can be used for Directed Acyclic Graph with negative weights. Since it doesn't have a negative cycle, it will not get caught in an infinite loop

  • @dipendrapratap6495
    @dipendrapratap6495 4 месяца назад

    If we will take nodes in a increasing order then that time I think we can find the distance in 2-3 iteration as well we don't need to do n-1 iterations

  • @psurya3053
    @psurya3053 2 года назад +1

    thank you bhaiyya , please can you make a playlist on examples on segment trees from codeforces

  • @rajeshj4066
    @rajeshj4066 Год назад +1

    @ 16:00 : explained why it has n-1 iterations

  • @120-venkataraghavareddyvar4
    @120-venkataraghavareddyvar4 Год назад +1

    I guess for the question why we need to do n-1 relaxations to each node is that ,, suppose we have 3 nodes directly connected a node and we have relaxed those nodes,, now in typical dijkstra algo,, the node with smallest value of relaxation will never get relaxed again, but if there are negative weights,, then there is a chance that the the node with smallest value of relaxation will get relaxed again. Since each node at max gets connected to n-1 nodes, so thus n-1 relaxations.

  • @HomiePlaysYT
    @HomiePlaysYT Год назад

    Why do I get a TLE when I don't mention this condition: dist[u] != 1e8 in the if statement? Why did we need to specifically mention this as I thought it would handle it by itself.

  • @Mandh-c7r
    @Mandh-c7r 6 месяцев назад

    what if we sort the given input such that the src node is at the start and so on......will we be able to to compute it all in just 1 relaxation then?

  • @asktostranger8296
    @asktostranger8296 2 года назад +1

    Bahi abhi graph ki kitni video he
    Aur bachi
    He
    Big fan 😍🙏

  • @UtpalPodder-IITian
    @UtpalPodder-IITian 7 месяцев назад

    Presense of negative edge does not always result incorrect result ...that could be easily proved in the second example if there is a path say from 4 to 3 with -1 edge weight ....but if the negative edge cycle change the previous path length which we got after n-1 iteration then it cause problem.

  • @bhargavreddy5938
    @bhargavreddy5938 2 года назад

    Well explained man ❤️

  • @kushalkollu8628
    @kushalkollu8628 5 месяцев назад

    striver bhai is goated

  • @sunnyyt4082
    @sunnyyt4082 9 месяцев назад

    can we consider the no of iterations as maximum path length from source?

  • @auroshisray9140
    @auroshisray9140 2 года назад

    Well explained bhai!

  • @vyomyadav6497
    @vyomyadav6497 Год назад

    Good, well explained.

  • @MojnoSardar
    @MojnoSardar Год назад

    Very well explained.

  • @YourITGuy9
    @YourITGuy9 2 года назад +2

    at 17.25 Edges are 5 i think u r referring to the no of nodes not edges

  • @VrundLeuva-g5s
    @VrundLeuva-g5s 7 месяцев назад

    very nice explanation

  • @Shivanai_h
    @Shivanai_h 2 года назад

    👏 understood...very well explained..

  • @saniyaverma914
    @saniyaverma914 8 месяцев назад

    Understood, thank you bhaiya

  • @stark2461
    @stark2461 Год назад

    In Case of Negative weight cycles, Dijkstra don't run forever. It produces wrong answer

  • @PriyanshLohiya-m1b
    @PriyanshLohiya-m1b Год назад +1

    What if we use topological sort Then it can be done in one iteration??

  • @ketanlalcheta4558
    @ketanlalcheta4558 2 года назад +1

    What's the use case of negative edge weight in reality?

    • @anonymous10906
      @anonymous10906 Год назад

      think of displacement (since it can be -ve)

  • @presidenttalks8
    @presidenttalks8 Месяц назад

    understood , thank you sir

  • @anonymous-zi5tt
    @anonymous-zi5tt 7 месяцев назад

    I had this small question, we dont have exact infinity in implemntation so, suppose we have 1e9, then at some condition of negative edge weight 1e9-2 > 1e9 would we true?

  • @gangsta_coder_12
    @gangsta_coder_12 2 года назад +1

    Understood 🔥🔥

  • @tasneemayham974
    @tasneemayham974 8 месяцев назад

    I have a question: the only reason we do N-1 iterations is because the node might be ordered from end to beginning with the source at the end and its connected node after. What if we re-write the graph such that the first edge is always the source and so on.. till the end? Will that need N-1 iterations now?

  • @chitranshkulshrestha485
    @chitranshkulshrestha485 6 месяцев назад

    Thanks for the intution