Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <style>
    circle {
        fill: blueviolet;
    }

    line {
        stroke-width: 1px;
        stroke: brown;
    }
</style>

<svg id="svg" xmlns="http://www.w3.org/2000/svg"></svg>
<script>
  // 并查集的实现,新开一篇博客再说
    function UnionFind(n, key) {

        if (!(this instanceof UnionFind))
            return new UnionFind(n);

        if (key && typeof key != 'function') {
            throw new Error("key has to be a function or else left undefined");
        }

        var cnt, id, sz, length;
        key = key || function (a) { return a; };


        cnt = length = n;
        id = new Array(n);
        sz = new Array(n);
        for (var i = 0; i < n; i++) {
            id[i] = i;
            sz[i] = 1;
        }

        this.size = function () {
            return length;
        };

        this.count = function () {
            return cnt;
        };

        this.find = function (p) {
            p = key(p);
            while (p != id[p]) {
                id[p] = id[id[p]];
                p = id[p];
            }

            return p;
        };

        this.connected = function (p, q) {
            p = key(p);
            q = key(q);
            ensureIndexWithinBounds(p, q);
            return this.find(p) === this.find(q);
        };

        this.union = function (p, q) {
            p = key(p);
            q = key(q);
            ensureIndexWithinBounds(p, q);
            var i = this.find(p)
                , j = this.find(q);

            if (i === j) return;

            if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; }
            else { id[j] = i; sz[i] += sz[j]; }

            cnt--;
            return;
        };

        function ensureIndexWithinBounds(args) {
            for (var i = arguments.length - 1; i >= 0; i--) {
                var p = arguments[i];
                if (p >= length)
                    throw new Error("Index out of bounds. The maximum index can be length-1");
            }
        }
    }
</script>
<script>
    var width = document.body.clientWidth;
    var height = window.innerHeight;
    var svg = document.getElementById("svg");
    var dots = 1000; // 生成 1k 个图节点
    var i = 0;
    var allCircle = [];
    const namespace = "http://www.w3.org/2000/svg";

    svg.setAttribute("width", width);
    svg.setAttribute("height", height);

    for (; i < dots; i++) {
        allCircle.push({
            cx: ~~(Math.random() * width),
            cy: ~~(Math.random() * height)
        });
    }

    class Graph {
        constructor(dots) {
            this.dots = dots;
            this.matrix = [];
            this.visited = [];
            this.lines = [];

            this.drawDots();
            this.adjacencyMatrix();

            console.time('time')
            this.kruskalMST();
            console.timeEnd('time')

            this.drawLines();
        }
        adjacencyMatrix() {
            var dots = this.dots;
            var length = dots.length;

            for (var i = 0; i < length; i++) {
                this.matrix[i] = [];
                for (var j = 0; j < length; j++) {
                    this.matrix[i][j] =
                        i !== j ? this.getDistance2(dots[i], dots[j]) : Number.MAX_SAFE_INTEGER;
                }
            }
        }
        kruskalMST() {
            var matrix = this.matrix;
            var matrixLength = matrix[0].length;
            var i;
            var j;
            var edges = [];
            var edge;
            var uf = new UnionFind(matrixLength);
            var sortedEdgeLength;

            for (i = 0; i < matrixLength; i += 1) {
                // 注意这里的循环,j 从 i + 1 开始,避免将重复的边(0-1,1-0)和自身(0-0,1-1)放入所有的边集合里,更高效
                for (j = i + 1; j < matrixLength; j += 1) {
                    edges.push({
                        fromIndex: i,
                        toIndex: j,
                        from: this.dots[i],
                        to: this.dots[j],
                        weight: this.matrix[i][j]
                    })
                }
            }

            edges = edges.sort(function (a, b) { // 将所有的边从小到大排序
                return a.weight - b.weight
            })

            sortedEdgeLength = edges.length

            for (i = 0; i < sortedEdgeLength; i += 1) {
                edge = edges[i]
                if (!uf.connected(edge.fromIndex, edge.toIndex)) { // 顶点没有连接则表示属于最小生成树的一边
                    this.lines.push(edge)
                    uf.union(edge.fromIndex, edge.toIndex);

                    if (uf.count() === 1) { // 表示取到所有所需的边,及时结束循环,更高效
                        break;
                    }
                }
            }
            console.log(edges.length, i)
        }
        getDistance2(p1, p2) {
            return ~~Math.sqrt((p1.cx - p2.cx) ** 2 + (p1.cy - p2.cy) ** 2);
        }
        drawDots() {
            this.dots.forEach(ele => {
                var dot = document.createElementNS(namespace, "circle");

                dot.setAttribute("cx", ele.cx);
                dot.setAttribute("cy", ele.cy);
                dot.setAttribute("r", 2);

                svg.appendChild(dot);
            });
        }
        drawLines() {
            var i = 0;
            var draw = () => {
                var line = document.createElementNS(namespace, "line");
                var _ = this.lines[i]

                if (_) {
                    line.setAttribute("x1", _.from.cx);
                    line.setAttribute("y1", _.from.cy);

                    line.setAttribute("x2", _.to.cx);
                    line.setAttribute("y2", _.to.cy);

                    svg.appendChild(line);
                }

                i++;
                if (i < this.lines.length) {
                    requestAnimationFrame(draw);
                }
            };

            draw();
        }
    }

    var g = new Graph(allCircle);
    console.log(g);
</script>

              
            
!

CSS

              
                
              
            
!

JS

              
                
              
            
!
999px

Console