@@ -374,6 +374,79 @@ best (v, e) pair from the IPQ. Mark node v as visited and add edge e to the MST.
374
374
Lastly, relax all edges of v while making sure not to relax any edge pointing to
375
375
a node which has already been visited.
376
376
377
+ @118.
378
+ Alright, let's see an example. Suppose we have the following weighted undirected
379
+ graph and we want to find any MST.
380
+
381
+ @119.
382
+ One thing to remember is that while we're dealing with an undirected graph I
383
+ will be internally representing it as a directed graph where each undirected
384
+ edge is stored as two directed edges.
385
+
386
+ @120.
387
+ I will also be keeping track of all (node, edge) key-value pairs on the right
388
+ and update them accordingly as the algorithm executes.
389
+
390
+ @121.
391
+ Let's begin the algorithm on node 0 and start iterate over all the edges of 0
392
+ and relax all of them. During the relaxing process add a (node, edge) pair to
393
+ the IPQ if it does not yet exist, or update the value if is has a better cost.
394
+
395
+ @122.
396
+ The first (node, edge) pair we add is node 2 with the incoming edge from 0 to 2
397
+ with cost 0 and similarly for the rest of node 0's edges.
398
+
399
+ @123. <press>
400
+ @124. <press>
401
+ @125. <press>
402
+ @126. <press>
403
+
404
+ @127.
405
+ The next best (node, edge) pair based on minimum edge cost is node 2 with the
406
+ incoming edge from node 0.
407
+
408
+ @128. <press>
409
+
410
+ @129.
411
+ Now iterate through all the edges of node 2 and relax all edges. Care to ignore
412
+ edges pointing to already visited nodes like on this slide.
413
+
414
+ @130.
415
+ The edge (2, 5, 6) has a better cost going to node 5 than the edge from node 0
416
+ to node 5 with cost 7, so update the IPQ with the new edge. I will denote IPQ
417
+ updates with a purple box around the edge being updated.
418
+
419
+ @131. <press>
420
+
421
+ @132.
422
+ The next best node-edge pair is node 3 with the edge coming from node 0 with a
423
+ cost of 5.
424
+
425
+ @133.
426
+ Now iterate through all the edges of node 3 and relax all edges.
427
+
428
+ @134. <press>
429
+
430
+ @135.
431
+ The edge coming from node 3 offers a better value so update the value for node 1
432
+ in the IPQ with the new edge.
433
+
434
+ @136.
435
+ Add the new key-value pair entry for node 6
436
+
437
+ @137.
438
+ Update the value for node 5 with the new better edge.
439
+
440
+ @138.
441
+ From this point on I will let the animation play.
442
+
443
+ ...
444
+
445
+ @164.
446
+ And that's
447
+
448
+
449
+
377
450
378
451
379
452
0 commit comments