File size: 23,826 Bytes
7d0bb4d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
# Example Gallery

This gallery showcases various animations for popular algorithms, created using the manim_dsa plugin. Each example is accompanied by code snippets and a brief explanation to help you understand how the algorithms are visualized and how to implement them in your own scenes.

## Bubble Sort

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. The process continues until the list is completely sorted.

Below is an animated visualization of Bubble Sort, where the comparison and swapping of elements are highlighted to make it easier to understand the sorting process. The animation also marks the sorted elements to clearly indicate progress.

<div id="bubblesort" class="admonition admonition-manim-example">
<p class="admonition-title">Example: BubbleSort <a class="headerlink" href="#bubblesort"></a></p><video
    class="manim-video"
    controls
    loop
    autoplay
    src="./BubbleSort-1.mp4">
</video>
```python
from manim import *

from manim_dsa import *

class BubbleSort(Scene):
    def bubblesort(self, arr):
        mArray = (
            MArray(arr, style=MArrayStyle.BLUE)
            .add_indexes()
        )
        self.play(Create(mArray))
        for i in range(len(arr)):
            for j in range(0, len(arr) - i - 1):
                # Highlight the elements being compared
                self.play(
                    mArray[j].animate.highlight(),
                    mArray[j+1].animate.highlight()
                )
                # Unhighlight after comparison
                self.play(
                    mArray[j].animate.unhighlight(),
                    mArray[j+1].animate.unhighlight()
                )
                # Swap if necessary
                if arr[j] > arr[j + 1]:
                    self.play(mArray.animate.swap(j, j+1))
                    arr[j], arr[j+1] = arr[j+1], arr[j]
            # Mark sorted element
            self.play(mArray[len(arr) - i - 1].square.animate.set_fill(GREEN))

    def construct(self):
        arr = [39, 85, 10, 2, 18]
        title = Text("Bubble Sort", font="Cascadia Code").scale(1.5).to_edge(UP)
        self.play(Create(title))
        self.bubblesort(arr)
```

<pre data-manim-binder data-manim-classname="BubbleSort">
from manim_dsa import \*

class BubbleSort(Scene):
    def bubblesort(self, arr):
        mArray = (
            MArray(arr, style=MArrayStyle.BLUE)
            .add_indexes()
        )
        self.play(Create(mArray))
        for i in range(len(arr)):
            for j in range(0, len(arr) - i - 1):
                # Highlight the elements being compared
                self.play(
                    mArray[j].animate.highlight(),
                    mArray[j+1].animate.highlight()
                )
                # Unhighlight after comparison
                self.play(
                    mArray[j].animate.unhighlight(),
                    mArray[j+1].animate.unhighlight()
                )
                # Swap if necessary
                if arr[j] > arr[j + 1]:
                    self.play(mArray.animate.swap(j, j+1))
                    arr[j], arr[j+1] = arr[j+1], arr[j]
            # Mark sorted element
            self.play(mArray[len(arr) - i - 1].square.animate.set_fill(GREEN))

    def construct(self):
        arr = [39, 85, 10, 2, 18]
        title = Text("Bubble Sort", font="Cascadia Code").scale(1.5).to_edge(UP)
        self.play(Create(title))
        self.bubblesort(arr)

</pre></div>

## Depth-First Search in a graph

Depth-First Search (DFS) is a graph traversal algorithm that starts at a source node and explores as far as possible along each branch before backtracking. DFS can be implemented using recursion or an explicit stack.
The following animations demonstrate both an iterative implementation of DFS using an explicit stack and a recursive implementation.

<div id="iterativedfs" class="admonition admonition-manim-example">
<p class="admonition-title">Example: IterativeDfs <a class="headerlink" href="#iterativedfs"></a></p><video
    class="manim-video"
    controls
    loop
    autoplay
    src="./IterativeDfs-1.mp4">
</video>
```python
from manim import *

from manim_dsa import *

class IterativeDfs(Scene):
    def dfs(self, graph, start):
        mGraph = (
            MGraph(graph, style=MGraphStyle.PURPLE)
            .scale(0.7).node_layout().to_edge(LEFT).shift(DR)
        )
        mStack = (
            MStack(style=MStackStyle.BLUE)
            .scale(0.7).to_edge(RIGHT).shift(DL)
        )
        self.play(Create(mGraph))
        self.play(Create(mStack))
        visited = {}
        stack = [start]
        prevList = [None]
        self.play(mStack.animate.append(start))
        for node in graph:
            visited[node] = False
        while stack:
            node = stack.pop()
            self.play(mStack.animate.pop())
            prev = prevList.pop()
            if prev and not visited[node]:
                self.play(mGraph[(prev, node)].animate.highlight())
            if not visited[node]:
                self.play(mGraph[node].animate.highlight())
            visited[node] = True
            for neighbor in graph[node]:
                if not visited[neighbor]:
                    stack.append(neighbor)
                    self.play(mStack.animate.append(neighbor))
                    prevList.append(node)

    def construct(self):
        graph = {
            '0': ['1', '2'], '1': ['0', '2', '3', '4'], '2': ['0', '1'],
            '3': ['1', '5'], '4': ['1'], '5': ['3', '6', '7', '8'], '6': ['5'],
            '7': ['5', '8'], '8': ['5', '7', '9'], '9': ['8']
        }
        start = '0'
        title = Text("Depth-First Search in a graph", font="Cascadia Code").to_edge(UP)
        self.play(Create(title))
        self.dfs(graph, start)
        self.wait()
```

<pre data-manim-binder data-manim-classname="IterativeDfs">
from manim_dsa import \*

class IterativeDfs(Scene):
    def dfs(self, graph, start):
        mGraph = (
            MGraph(graph, style=MGraphStyle.PURPLE)
            .scale(0.7).node_layout().to_edge(LEFT).shift(DR)
        )
        mStack = (
            MStack(style=MStackStyle.BLUE)
            .scale(0.7).to_edge(RIGHT).shift(DL)
        )
        self.play(Create(mGraph))
        self.play(Create(mStack))
        visited = {}
        stack = [start]
        prevList = [None]
        self.play(mStack.animate.append(start))
        for node in graph:
            visited[node] = False
        while stack:
            node = stack.pop()
            self.play(mStack.animate.pop())
            prev = prevList.pop()
            if prev and not visited[node]:
                self.play(mGraph[(prev, node)].animate.highlight())
            if not visited[node]:
                self.play(mGraph[node].animate.highlight())
            visited[node] = True
            for neighbor in graph[node]:
                if not visited[neighbor]:
                    stack.append(neighbor)
                    self.play(mStack.animate.append(neighbor))
                    prevList.append(node)

    def construct(self):
        graph = {
            '0': ['1', '2'], '1': ['0', '2', '3', '4'], '2': ['0', '1'],
            '3': ['1', '5'], '4': ['1'], '5': ['3', '6', '7', '8'], '6': ['5'],
            '7': ['5', '8'], '8': ['5', '7', '9'], '9': ['8']
        }
        start = '0'
        title = Text("Depth-First Search in a graph", font="Cascadia Code").to_edge(UP)
        self.play(Create(title))
        self.dfs(graph, start)
        self.wait()

</pre></div><div id="recursivedfs" class="admonition admonition-manim-example">
<p class="admonition-title">Example: RecursiveDfs <a class="headerlink" href="#recursivedfs"></a></p><video
    class="manim-video"
    controls
    loop
    autoplay
    src="./RecursiveDfs-1.mp4">
</video>
```python
from manim import *

from manim_dsa import *

class RecursiveDfs(Scene):
    def dfs_helper(self, graph, mGraph, visited, prev, root):
        visited[root] = True
        self.play(mGraph[root].animate.highlight())
        for adj in graph[root]:
            if(not visited[adj]):
                self.play(mGraph[(root, adj)].animate.highlight())
                self.dfs_helper(graph, mGraph, visited, prev, adj)
                self.play(mGraph[(root, adj)].animate.unhighlight())
        self.play(mGraph[root].animate.unhighlight())

    def dfs(self, graph, mGraph):
        visited = {}

        for node in graph:
            visited[node] = False

        for node in graph:
            if(not visited[node]):
                self.dfs_helper(graph, mGraph, visited, None, node)

    def construct(self):
        graph = {
            '0': ['1', '2'],
            '1': ['0', '2', '3', '4'],
            '2': ['0', '1'],
            '3': ['1', '5'],
            '4': ['1'],
            '5': ['3', '6', '7', '8'],
            '6': ['5'],
            '7': ['5', '8'],
            '8': ['5', '7', '9'],
            '9': ['8']
        }

        nodes_and_positions = {
            '0': LEFT * 6,
            '1': LEFT * 4 + UP,
            '2': LEFT * 4 + DOWN,
            '3': LEFT * 2,
            '4': LEFT * 2 + UP * 2,
            '5': ORIGIN,
            '6': LEFT * 2 + DOWN * 2,
            '7': RIGHT * 2 + DOWN * 2,
            '8': RIGHT * 2 + UP * 2,
            '9': RIGHT * 4 + UP * 2,
        }

        mGraph = MGraph(graph, nodes_and_positions, style=MGraphStyle.BLUE).move_to(ORIGIN).shift(DOWN/2)

        title = Text("Depth-First Search in a graph", font="Cascadia Code").to_edge(UP)

        self.play(Create(title))
        self.play(Create(mGraph))

        self.dfs(graph, mGraph)
        self.wait()
```

<pre data-manim-binder data-manim-classname="RecursiveDfs">
from manim_dsa import \*

class RecursiveDfs(Scene):
    def dfs_helper(self, graph, mGraph, visited, prev, root):
        visited[root] = True
        self.play(mGraph[root].animate.highlight())
        for adj in graph[root]:
            if(not visited[adj]):
                self.play(mGraph[(root, adj)].animate.highlight())
                self.dfs_helper(graph, mGraph, visited, prev, adj)
                self.play(mGraph[(root, adj)].animate.unhighlight())
        self.play(mGraph[root].animate.unhighlight())

    def dfs(self, graph, mGraph):
        visited = {}

        for node in graph:
            visited[node] = False

        for node in graph:
            if(not visited[node]):
                self.dfs_helper(graph, mGraph, visited, None, node)

    def construct(self):
        graph = {
            '0': ['1', '2'],
            '1': ['0', '2', '3', '4'],
            '2': ['0', '1'],
            '3': ['1', '5'],
            '4': ['1'],
            '5': ['3', '6', '7', '8'],
            '6': ['5'],
            '7': ['5', '8'],
            '8': ['5', '7', '9'],
            '9': ['8']
        }

        nodes_and_positions = {
            '0': LEFT \* 6,
            '1': LEFT \* 4 + UP,
            '2': LEFT \* 4 + DOWN,
            '3': LEFT \* 2,
            '4': LEFT \* 2 + UP \* 2,
            '5': ORIGIN,
            '6': LEFT \* 2 + DOWN \* 2,
            '7': RIGHT \* 2 + DOWN \* 2,
            '8': RIGHT \* 2 + UP \* 2,
            '9': RIGHT \* 4 + UP \* 2,
        }

        mGraph = MGraph(graph, nodes_and_positions, style=MGraphStyle.BLUE).move_to(ORIGIN).shift(DOWN/2)

        title = Text("Depth-First Search in a graph", font="Cascadia Code").to_edge(UP)

        self.play(Create(title))
        self.play(Create(mGraph))

        self.dfs(graph, mGraph)
        self.wait()

</pre></div>

## Prim’s Algorithm for Minimum Spanning Tree in a graph

Prim’s Algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. The algorithm starts with an arbitrary node and grows the tree by adding the minimum weight edge that connects the tree to a new node. The process continues until all nodes are included in the tree.

In the animation below, green edges represent the edges that are part of the minimum spanning tree, blue edges indicate the edges currently being considered in the iteration, and red edges denote the edges that are not part of the minimum spanning tree. In the end, the total weight of the minimum spanning tree is displayed.

<div id="prim" class="admonition admonition-manim-example">
<p class="admonition-title">Example: Prim <a class="headerlink" href="#prim"></a></p><video
    class="manim-video"
    controls
    loop
    autoplay
    src="./Prim-1.mp4">
</video>
```python
from manim import *

from manim_dsa import *
import heapq

class Prim(Scene):
    def prim(self, graph, nodes_and_positions, start):
        pq = []
        visited = {}

        mGraph = MGraph(graph, nodes_and_positions, style=MGraphStyle.PURPLE).move_to(ORIGIN)
        self.play(Create(mGraph))

        for node in graph:
            visited[node] = False

        res = 0

        heapq.heappush(pq, (0, None, start))

        while pq:
            wt, prev_node, u = heapq.heappop(pq)
            if visited[u]:
                self.play(mGraph[(prev_node, u)].animate.highlight(RED))
                continue

            visited[u] = True
            res += wt

            if prev_node is not None:
                self.play(mGraph[(prev_node, u)].animate.highlight(GREEN))

            self.play(mGraph[u].animate.highlight(GREEN))

            for adj in graph[u]:
                v, weight = adj
                if not visited[v]:
                    heapq.heappush(pq, (weight, u, v))
                    self.play(mGraph[(u, v)].animate.highlight(BLUE))

        return res

    def construct(self):
        graph = {
            '0': [('1', 2), ('2', 4)],
            '1': [('0', 2), ('2', 1), ('3', 5), ('4', 5)],
            '2': [('0', 4), ('1', 1)],
            '3': [('1', 5), ('5', 2)],
            '4': [('1', 5)],
            '5': [('3', 2), ('6', 7), ('7', 2), ('8', 1)],
            '6': [('5', 7)],
            '7': [('5', 2), ('8', 6)],
            '8': [('5', 1), ('7', 6), ('9', 3)],
            '9': [('8', 3)]
        }

        nodes_and_positions = {
            '0': LEFT * 6,
            '1': LEFT * 4 + UP,
            '2': LEFT * 4 + DOWN,
            '3': LEFT * 2,
            '4': LEFT * 2 + UP * 2,
            '5': ORIGIN,
            '6': LEFT * 2 + DOWN * 2,
            '7': RIGHT * 2 + DOWN * 2,
            '8': RIGHT * 2 + UP * 2,
            '9': RIGHT * 4 + UP * 2,
        }

        title = (
            Text("Prim's Algorithm for Minimum Spanning Tree", font="Cascadia Code")
            .scale(0.7).to_edge(UP)
        )
        self.play(Create(title))

        total_weight = self.prim(graph, nodes_and_positions, '0')

        text = (
            Text("Total: " + str(total_weight), font="Cascadia Code")
            .to_edge(DOWN)
        )
        self.play(Create(text))
        self.wait()
```

<pre data-manim-binder data-manim-classname="Prim">
from manim_dsa import \*
import heapq

class Prim(Scene):
    def prim(self, graph, nodes_and_positions, start):
        pq = []
        visited = {}

        mGraph = MGraph(graph, nodes_and_positions, style=MGraphStyle.PURPLE).move_to(ORIGIN)
        self.play(Create(mGraph))

        for node in graph:
            visited[node] = False

        res = 0

        heapq.heappush(pq, (0, None, start))

        while pq:
            wt, prev_node, u = heapq.heappop(pq)
            if visited[u]:
                self.play(mGraph[(prev_node, u)].animate.highlight(RED))
                continue

            visited[u] = True
            res += wt

            if prev_node is not None:
                self.play(mGraph[(prev_node, u)].animate.highlight(GREEN))

            self.play(mGraph[u].animate.highlight(GREEN))

            for adj in graph[u]:
                v, weight = adj
                if not visited[v]:
                    heapq.heappush(pq, (weight, u, v))
                    self.play(mGraph[(u, v)].animate.highlight(BLUE))

        return res

    def construct(self):
        graph = {
            '0': [('1', 2), ('2', 4)],
            '1': [('0', 2), ('2', 1), ('3', 5), ('4', 5)],
            '2': [('0', 4), ('1', 1)],
            '3': [('1', 5), ('5', 2)],
            '4': [('1', 5)],
            '5': [('3', 2), ('6', 7), ('7', 2), ('8', 1)],
            '6': [('5', 7)],
            '7': [('5', 2), ('8', 6)],
            '8': [('5', 1), ('7', 6), ('9', 3)],
            '9': [('8', 3)]
        }

        nodes_and_positions = {
            '0': LEFT \* 6,
            '1': LEFT \* 4 + UP,
            '2': LEFT \* 4 + DOWN,
            '3': LEFT \* 2,
            '4': LEFT \* 2 + UP \* 2,
            '5': ORIGIN,
            '6': LEFT \* 2 + DOWN \* 2,
            '7': RIGHT \* 2 + DOWN \* 2,
            '8': RIGHT \* 2 + UP \* 2,
            '9': RIGHT \* 4 + UP \* 2,
        }

        title = (
            Text("Prim's Algorithm for Minimum Spanning Tree", font="Cascadia Code")
            .scale(0.7).to_edge(UP)
        )
        self.play(Create(title))

        total_weight = self.prim(graph, nodes_and_positions, '0')

        text = (
            Text("Total: " + str(total_weight), font="Cascadia Code")
            .to_edge(DOWN)
        )
        self.play(Create(text))
        self.wait()

</pre></div>

## Kruskal’s Algorithm for Minimum Spanning Tree in a graph

Kruskal’s Algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. The algorithm starts with an empty tree and adds the minimum weight edge that does not form a cycle in the tree. The process continues until all nodes are included in the tree.

In the animation below, green edges represent the edges that are part of the minimum spanning tree and red edges denote the edges that are not part of the minimum spanning tree. In the end, the total weight of the minimum spanning tree is displayed.

<div id="kruskal" class="admonition admonition-manim-example">
<p class="admonition-title">Example: Kruskal <a class="headerlink" href="#kruskal"></a></p><video
    class="manim-video"
    controls
    loop
    autoplay
    src="./Kruskal-1.mp4">
</video>
```python
from manim import *

from manim_dsa import *
import heapq

class Kruskal(Scene):
    def find(self, parent, i):
        if parent[i] == i:
            return i
        return self.find(parent, parent[i])

    def union(self, parent, rank, x, y):
        xroot = self.find(parent, x)
        yroot = self.find(parent, y)
        if rank[xroot] < rank[yroot]:
            parent[xroot] = yroot
        elif rank[xroot] > rank[yroot]:
            parent[yroot] = xroot
        else:
            parent[yroot] = xroot
            rank[xroot] += 1

    def kruskal(self, graph, nodes_and_positions):
        mGraph = MGraph(graph, nodes_and_positions, style=MGraphStyle.PURPLE).move_to(ORIGIN)
        self.play(Create(mGraph))

        edges = []
        for u in graph:
            for v, weight in graph[u]:
                if (weight, u, v) not in edges and (weight, v, u) not in edges:
                    edges.append((weight, u, v))
        edges.sort()

        parent = {}
        rank = {}

        for node in graph:
            parent[node] = node
            rank[node] = 0

        mst_weight = 0

        for edge in edges:
            wt, u, v = edge
            x = self.find(parent, u)
            y = self.find(parent, v)
            if x != y:
                self.play(mGraph[(u, v)].animate.highlight(GREEN, 12))
                mst_weight += wt
                self.union(parent, rank, x, y)
            else:
                self.play(mGraph[(u, v)].animate.highlight(RED, 12))

        return mst_weight


    def construct(self):
        graph = {
            '0': [('1', 2), ('2', 4)],
            '1': [('0', 2), ('2', 1), ('3', 5), ('4', 5)],
            '2': [('0', 4), ('1', 1)],
            '3': [('1', 5), ('5', 2)],
            '4': [('1', 5)],
            '5': [('3', 2), ('6', 7), ('7', 2), ('8', 1)],
            '6': [('5', 7)],
            '7': [('5', 2), ('8', 6)],
            '8': [('5', 1), ('7', 6), ('9', 3)],
            '9': [('8', 3)]
        }

        nodes_and_positions = {
            '0': LEFT * 6,
            '1': LEFT * 4 + UP * 2,
            '2': LEFT * 4 + DOWN * 2,
            '3': LEFT * 2,
            '4': LEFT * 2 + UP * 2,
            '5': ORIGIN + RIGHT,
            '6': LEFT + DOWN * 2,
            '7': RIGHT * 3 + DOWN * 2,
            '8': RIGHT * 3 + UP * 2,
            '9': RIGHT * 5 + UP * 2,
        }

        title = Text("Kruskal’s Algorithm for Minimum Spanning Tree", font="Cascadia Code").scale(0.7).to_edge(UP)
        self.play(Create(title))
        total_weight = self.kruskal(graph, nodes_and_positions)
        text = Text("Total: " + str(total_weight), font="Cascadia Code").to_edge(DOWN)
        self.play(Create(text))
        self.wait()
```

<pre data-manim-binder data-manim-classname="Kruskal">
from manim_dsa import \*
import heapq

class Kruskal(Scene):
    def find(self, parent, i):
        if parent[i] == i:
            return i
        return self.find(parent, parent[i])

    def union(self, parent, rank, x, y):
        xroot = self.find(parent, x)
        yroot = self.find(parent, y)
        if rank[xroot] < rank[yroot]:
            parent[xroot] = yroot
        elif rank[xroot] > rank[yroot]:
            parent[yroot] = xroot
        else:
            parent[yroot] = xroot
            rank[xroot] += 1

    def kruskal(self, graph, nodes_and_positions):
        mGraph = MGraph(graph, nodes_and_positions, style=MGraphStyle.PURPLE).move_to(ORIGIN)
        self.play(Create(mGraph))

        edges = []
        for u in graph:
            for v, weight in graph[u]:
                if (weight, u, v) not in edges and (weight, v, u) not in edges:
                    edges.append((weight, u, v))
        edges.sort()

        parent = {}
        rank = {}

        for node in graph:
            parent[node] = node
            rank[node] = 0

        mst_weight = 0

        for edge in edges:
            wt, u, v = edge
            x = self.find(parent, u)
            y = self.find(parent, v)
            if x != y:
                self.play(mGraph[(u, v)].animate.highlight(GREEN, 12))
                mst_weight += wt
                self.union(parent, rank, x, y)
            else:
                self.play(mGraph[(u, v)].animate.highlight(RED, 12))

        return mst_weight


    def construct(self):
        graph = {
            '0': [('1', 2), ('2', 4)],
            '1': [('0', 2), ('2', 1), ('3', 5), ('4', 5)],
            '2': [('0', 4), ('1', 1)],
            '3': [('1', 5), ('5', 2)],
            '4': [('1', 5)],
            '5': [('3', 2), ('6', 7), ('7', 2), ('8', 1)],
            '6': [('5', 7)],
            '7': [('5', 2), ('8', 6)],
            '8': [('5', 1), ('7', 6), ('9', 3)],
            '9': [('8', 3)]
        }

        nodes_and_positions = {
            '0': LEFT \* 6,
            '1': LEFT \* 4 + UP \* 2,
            '2': LEFT \* 4 + DOWN \* 2,
            '3': LEFT \* 2,
            '4': LEFT \* 2 + UP \* 2,
            '5': ORIGIN + RIGHT,
            '6': LEFT + DOWN \* 2,
            '7': RIGHT \* 3 + DOWN \* 2,
            '8': RIGHT \* 3 + UP \* 2,
            '9': RIGHT \* 5 + UP \* 2,
        }

        title = Text("Kruskal’s Algorithm for Minimum Spanning Tree", font="Cascadia Code").scale(0.7).to_edge(UP)
        self.play(Create(title))
        total_weight = self.kruskal(graph, nodes_and_positions)
        text = Text("Total: " + str(total_weight), font="Cascadia Code").to_edge(DOWN)
        self.play(Create(text))
        self.wait()

</pre></div>