G-42. Floyd Warshall Algorithm

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

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

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

    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

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

      Thank you soooooo much!!! Understood!!!!!❤❤

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

      di[i][[j] = Min(d[i][k]+d[k][j]) right ?,u said d[j][k] dont know why

    • @AJ-xc3ks
      @AJ-xc3ks Год назад

      @@sairam3351 min(d[i][k] + d[k][j]) is right..

  • @mohanjha4397
    @mohanjha4397 10 месяцев назад +11

    People say Graph is a difficult Topic, but after going through striver's i haven't faced any problem.so you are a genius.😊

  • @AbhrajyotiKundu00
    @AbhrajyotiKundu00 2 года назад +163

    Yes, this is how addiction is built over Algorithms! Thank you Striver :)

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

      Job lgi?

    • @ITACHIUCHIHA-dr8sz
      @ITACHIUCHIHA-dr8sz 6 месяцев назад

      @@anonymousanonymous7507 savage!!

    • @chetanraghavv
      @chetanraghavv 3 месяца назад +7

      @@anonymousanonymous7507 he's pursuing MTech in CSE from IIT Guwahati. Har jagah cool nahi banna hota, strangers ke saamne cool banne ki naakam koshish karne se achha hai khudpe mehnat karo aur aage badho life me

    • @noroomstash2098
      @noroomstash2098 2 месяца назад +1

      @@chetanraghavv the guy who ur calling cool is doing Mtech from Harvard . two steps ahead

  • @shikharshiromani2728
    @shikharshiromani2728 2 года назад +322

    At 5:39, I think it should be min(d[i][k] + d[k][j])

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

      Yes, a small typo..

    • @saranghae3720
      @saranghae3720 2 года назад +34

      Hey, Striver, Pin this comment or write this in ur already pinned comment.

  • @lavanya_m01
    @lavanya_m01 10 месяцев назад +6

    I feel like sitting in a maths class. Amazing explanation! You made a complex algorithm look very simple. Thanks a ton Striver!

  • @shikharsrivastava8600
    @shikharsrivastava8600 Год назад +25

    Hey striver, the way you explained was quite commendable.
    Just at 26:58 , we should add extra if(matrix[i][k] != 1e9 && matrix[k][j] != 1e9) condition to make sure we don’t go via unreachable nodes.

    • @KUMARSAURABH-s5i
      @KUMARSAURABH-s5i 7 месяцев назад

      No need for it since we are taking min of both so even if all of them are 1e9 the result will still be 1e9

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

      @@KUMARSAURABH-s5i in case of negative edges followed by an 1e9 edge. this will pose problem. so i think if condition should be proposed

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

      @@KUMARSAURABH-s5i no through we can reduce litte time

  • @king-akash1479
    @king-akash1479 Год назад +9

    I really like the prompt that comes in which a message comes explaining what we should focus on. :)

  • @KSSRINIVASEAEB
    @KSSRINIVASEAEB 27 дней назад +2

    Thankyou for the pop-up at 22:42 it gave me relief!

  • @saurabhsangam2737
    @saurabhsangam2737 Год назад +16

    5:46 The equation should be minimum of (d [I] [k] + d [k] [j] ) for calculating for path I => k => j

  • @MusaafirSonu
    @MusaafirSonu 9 месяцев назад +6

    After watching lots of video , I can only understand this video .
    Thank you Striver .❤

  • @DeepakKumar-oz5ky
    @DeepakKumar-oz5ky 4 месяца назад +2

    thank you so much striver for great explanation. you are such a man who know how teach the students.

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

    Amazing teaching as usual Striver.
    If you continue to teach this depth in Graph , you will soon device your own algorithm one day for sure.

  • @chidam333
    @chidam333 10 месяцев назад +2

    thank you so much ! i was panicking while revising as i couldn't get the intuition properly when revising!! Your 22:48 footnote was really helpful

  • @user-rdr1712
    @user-rdr1712 3 месяца назад +4

    Floyd Warshal Algorithm:
    1) Initialise dp(N x N) with Infinity.
    2) Update dp[i][i] = 0;
    3) Update given edge's weight in dp.
    4) We need to find the minDistance from i to j via each node.
    5) dp[i][j] = dp[i][via] + dp[via][j];
    6) As a result, dp will have the min distance from any-to-any nodes of graph.

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

    INTUITION(correct me if im wrong):
    We can think of 'via' as an intermediate node we must hop thru to get to destination( kind of like connecting flight(the second plane)).
    Therefore, after performing via 'nth' node, we have found shortest paths for node 'nth-1' as source where it touches nth node as intermediate node.
    Ex:After processing via node1, we were able to update shortest path from node0 to node2 because node1 as intermediate offered shorter path.
    See @17:10

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

    Best graph playlist on youtube.
    You are the great sir.

  • @evergreen7781
    @evergreen7781 2 месяца назад

    Yet another most beautiful explanation on RUclips !!!

  • @The_Shubham_Soni
    @The_Shubham_Soni Год назад +12

    People say Graph is a difficult Topic, but after going through striver's series i haven't faced any problem. Moreover i find it Super Easy🤩

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

    I can´t say enough, how much i love your videos

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

    Understood! Such a fantastic explanation as always, thank you very much!

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

    Habibi katai bawaal macha rakhe ho ...1 number.chiz hai ye toh

  • @HEMANTPORWAL-t7d
    @HEMANTPORWAL-t7d 13 дней назад

    23:14
    at this graph at nth itteration
    [0][0] via 2 is [0][2] + [2][0] is equal to -5 +2 = -3 which is smaller than zero
    hence It confirms negative cycle because [I][I] should be zero

  • @preetkatiyar969
    @preetkatiyar969 2 года назад +4

    THIS IS REAL THAT SOMETHING WE WANT AND I GURENTEED NO ONE CAN TEACH BETTER THAN THIS EVEN IN PAID COURSES OF LAKHS.

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

    Understood and I too understood your effort which is incredible.

  • @ayushrai6699
    @ayushrai6699 2 года назад +10

    (V*E * logV) > (V^3)... right? As in worst case E is V*(V-1). So Floyd Warshall is better than Dijkstras for shortest path to all the nodes from multiple source in contrast to what striver said at 29:08

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

      E is V x V-1 is a very very very rare and dense graph..

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

      @@takeUforward Agreed but in interview we are supposed to give worst case time complexity... right? Or am I missing something?

    • @ravisingh-el8np
      @ravisingh-el8np Год назад +1

      ​@@ayushrai6699yes you're right don't worry

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

    Can't thank u enough! Striver 🔥

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

    understood! thanks Striver, the explanation is 🔥

  • @mayankkumar6997
    @mayankkumar6997 2 года назад +32

    A small doubt at the last, if we apply dijkstra algorithm for finding all pair shortest path, then time complexity is = V E logV. But if it is complete graph then E approximate V^2. So final time complexity becomes V^3 logV, then how its better from floyd warshall algorithm!

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

      Usually you don't get complete graphs always..

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

      I agree with mayank here. If you try to solve the ‘Find the city with smallest neighbours in a threshold’ leetcode problem using Dijkstra’s using set, the time taken is much higher than a simple Floyd warshal solution.
      Solving it through PQ gives a TLE.

    • @ArdentMusicLover
      @ArdentMusicLover 2 месяца назад +2

      @mayankkumar6997: The ELogV for Djikstra's algorithm is Worst Case complexity. It's actual Elog(V^2 ) because in the worst case, the min heap will have V*(V-1) entries in the heap, which approximated to V^2. And that is O(2ElogV), which is O(ElogV). If you repeat that for V vertices, then time complexity is V*O(ElogV) . That outside V cannot be multipled with E.
      Another thing to note is that FloydWarshal is always O(V^3)

    • @noroomstash2098
      @noroomstash2098 2 месяца назад

      @@ArdentMusicLover wait why cant the V be multiplied with the E inside

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

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

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

    As Striver said always explain why DJ would not work with -ve weights and cycle hence we need to use Floyd Warshal

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

    24:24 :that evil smile @takeUforward😁😂

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

    The voice editing is OP💥

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

    Thank you so much! Awesome explaination!~!

  • @fraudulentme
    @fraudulentme Год назад +7

    Another point:
    Even if all the weights are positive, why Dijkstra might not be preferred over Floyd Warshall is because for Dijkstra, time complexity is
    V * E * log(V)
    For dense graphs,
    E ~ V^2 since E = V (V-1)/2 for a fully connected graph
    Making the time complexity
    V^3 * log(V)
    Tell me if I interpreted that correctly.

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

      yes

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

      Bro Djikstra time Complexity is O(V + E)Log V and if there is a dense graph then E = V^2 that makes it O(V^2 LogV) which is better than Floyd Warshall

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

      @@pulkitgupta669 bro, we are doing dijkstra for all the nodes so, time complexity will be V * whatever u calculated, which is at worst V^3 log(V), whereas floyd warshall has V^3

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

      @@CEBMANURBHAVARYA Yeah sorry I miscalculated. Thank you for helping.

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

    I know it is an old debate whether modifying the input counts as extra space but if you are instructed to do the solution IN-PLACE then I would argue that it shouldn't count as extra space. For example, Sorting is almost always done in-place and you never see the space complexity analysis include the size of the list that is being sorted.

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

    Understood sir! thank you so much

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

    understood, thanks for the great explanation

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

    understood just awesome explanation

  • @AYUSHKUMAR-xj4wc
    @AYUSHKUMAR-xj4wc Год назад

    Awesome Explanation❤❤❤

  • @user-jc5vo9sz3l
    @user-jc5vo9sz3l Год назад

    A very fantastic explanation ❤

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

    Thank you sir 🙏

  • @Chandraprakash-kx4ic
    @Chandraprakash-kx4ic Год назад

    love u striver...Thanku sooo much

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

    striver understood!!!! thankyou!!!👍

  • @studynewthings1727
    @studynewthings1727 3 месяца назад +2

    I want to criticize you striver not using the correct infinity symbol.😅

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

    Thank you striver!

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

    2:20 - 16:00
    23:00 - 24:02

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

    My favorite algo

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

    u r the true gem🤩

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

    understood, nice video, well explained

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

    Understood bhaiya 🙏❤️

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

    Good explanation

  • @IndhujaB-y7h
    @IndhujaB-y7h Год назад +1

    Hey Striver, i have an doubt
    the graph you use here,ends with infinity(in the final matrix) so does that mean there is no shortest path for such nodes???

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

    well explained thank you!

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

    Thank you very much. You are a genius.

  • @IK-xk7ex
    @IK-xk7ex Год назад

    Awesome. thank you for explanation

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

    Great explanation!

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

    Love your content striver just want to tell you forgot to write the if statement -:
    if(matrix[i][k] != 1e9 && matrix[k][j]!=1e9) before
    matrix[i][j] = min(matrix[i][j], matrix[i][k] + matrix[k][j]);
    If we dono't add this condition then if fail for below test case
    For Input:
    3
    0 -1 -1
    -1 0 -2
    -1 -1 0
    Your Output:
    0 -1 999999998
    999999998 0 -2
    -1 -1 0
    Expected Output:
    0 -1 -1
    -1 0 -2
    -1 -1 0

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

      void shortest_distance(vector&mat){
      int n = mat.size();
      for(int via=0; via

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

    Understood 🔥🔥

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

    Understood bhaiya!!

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

    For someone thinking whether can we detetct negative cycle similarly as we detected here by checking the distance[source]

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

    understood 💯

  • @TarunKumar-jg4jz
    @TarunKumar-jg4jz Год назад +1

    Is it not possible to apply "bellman ford" for all the vertices and store in 2d array for result. ??

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

    amazing explanation *understood*

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

    hats off to you bhaiya

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

    Amazing explanation !

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

    actually if edges is more than V^2/log(v) then the floyd warshall is more optimal then dijkstar algo

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

    what about the conditions where infinity is added to infinity and gives negative result ?

    • @lakshmanchandukondreddy1720
      @lakshmanchandukondreddy1720 9 месяцев назад +1

      To avoid that we have to if condition like this if(matrix[i][k]!=1e9 and matrix[k][j]!=1e9)

  • @ShivamKendre-fc3su
    @ShivamKendre-fc3su Год назад

    Thank you so much

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

    best.PERIOD.

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

    where is the mathematical proof, that the approach gives the correct ans?

  • @nalamanuraag802
    @nalamanuraag802 17 дней назад

    I have a small doubt here, while computing the shortest path by considering node 1 as the intermediary, why are we computing values from that matrix where 0th node is considered as intermediary and not the original matrix? Can anyone help me out with this?
    Thanks

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

    understood🔥🔥

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

    understood sir ❤❤

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

    Great Video

  • @rohitkumar-dc3xb
    @rohitkumar-dc3xb 7 месяцев назад

    One thing i don't get it u say even if we use same matrix still we are using O(n*n) time complexity, but in array problems if we try to find the answer using same array without using any extra space we say TC is O(1). Isn't it contracdicting ?
    Btw nice explaination.....

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

      the O(1) you mentioned is space complexity my friend, not time complexity.

  • @myemptymirror
    @myemptymirror 2 месяца назад

    Path Printing?

  • @KunalSingh-kn2ij
    @KunalSingh-kn2ij Год назад +2

    why the code is giving wrong output if we are using INT_MAX instead of 1e9?

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

      Out of bounds

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

      even if you add +1 to int max it goes out of bounds and produces error . hence always use 1e9 or 1e8 for graph algos

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

    Why the code not giving integer overflow in the min function whenever adding with 1e9 plus something

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

      When two numbers that are close to INT_MAX are added, the result can exceed the maximum value that
      can be stored in an int, causing overflow. Overflow wraps around to negative values, which would then be incorrectly considered as a shorter path.
      Using 1e9 even if you add two paths with this maximum value, you get 2e9, which is still within the range of a 32-bit integer.

  • @VishaliniT-f3g
    @VishaliniT-f3g 6 месяцев назад

    Understood 👍☺️

  • @DreamLife-05
    @DreamLife-05 2 года назад

    Understood 🙌💯

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

    Understood ❤❤

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

    Hi! need help with the Space complexity
    Here striver mentioned that space complexity is n3(n*n*n) meaning we consider the space we use in solving the problem which here is the original matrix,lets take an example of bubble sort there also we use the same array to sort it, no other array is considered to solve but there the time complexity is not n but o(1) ? why is that am i missing onto something..
    please reply if you have any clue.. Thankyou

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

    I am thinking if i apply djikstra for all edges then the time complexity will be
    O(V.ElogV) . I am thinking it is better than O(V^³).
    Please correct me

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

    understood brother

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

    why we are using (via) loop first i.e for every i,j check for via k first ...... why cant we check for a particular i,j with all the vias first and then move to next i,j(means we take k loop as the third loop instead of first loop)?

    • @some-good-stuff
      @some-good-stuff 6 месяцев назад

      did u get an answer cuz it fails and i dont understand why it fails

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

    5.39,
    a small correction,
    dis[i][j] = min(dis[i] [k] + dis[k] [j]);

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

    Understood, any problem using this algorithm?

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

    Understood!

  • @SmitShah-m1m
    @SmitShah-m1m Год назад

    Understood Sir

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

    why are you saying...when undirected graph will be given change it to directed by making two edges...it's not already understood because of the adjacency matrix( which already has edge weight filled)

    • @anvesh5377
      @anvesh5377 2 года назад +5

      Bro everytime they don't give adj list or adj matrix . They say it is undirected graph and edges will be given then u have to creare and fill adj matrix with two way edges

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

      Ohh thanks

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

    Hi , what if i make my loop like this ,
    For ( i loop )
    For ( j loop )
    For ( intermediate loop)
    ..i am getting wrong ans if i make loop like this , can you tell why intermediate loop should be on first , acc to me it can be at last also.

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

      I also have same doubt if you know its answer then please reply

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

      If you think about it, you are actually changing the algorithm by doing this. In the original algorithm you are updating the matrix for each intermediate vertex one by one. In your case you are going to update each node for each via at one go which is actually a different algorithm. Think of it like bellman ford, the changes take n steps to propogate to all nodes. You are updating each node at one go without the changes propogating

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

    why
    if == -1 ?
    condition not get it

  • @-VLaharika
    @-VLaharika Год назад

    Understood 👍

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

    understood😊😊

  • @DIVANSHUSHARMA-cw5pj
    @DIVANSHUSHARMA-cw5pj Год назад

    Thank you bhaiya

  • @lonewolf-_-8634
    @lonewolf-_-8634 Год назад

    UNDERSTOOD

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

    understood ++, Addicted bruhh with graph playlist, Thanks a lot @raj

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

    striver my data is lost on your website after my mac has updated. I have made important notes on your website. What should I do now?

  • @ACUCSPRADEEPB-up9ne
    @ACUCSPRADEEPB-up9ne 2 года назад

    Understood✌️

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

    thanks man