zoukankan      html  css  js  c++  java
  • [Algorithm] JavaScript Graph Data Structure

    A graph is a data structure comprised of a set of nodes, also known as vertices, and a set of edges. Each node in a graph may point to any other node in the graph. This is very useful for things like describing networks, creating related nonhierarchical data, and as we will see in the lesson, describing the relationships within one's family.

    In a Graph, there are Nodes, and connects between nodes are Edges.

    For node:

    function createNode(key) {
        let children = [];
        return {
            key,
            children, // the nodes which connect to
            addChild(child) {
                children.push(child)
            }
        }
    }

    Graph:

    function createGraph(directed = false) {
        const nodes = [];
        const edges = [];
    
        return {
            nodes,
            edges,
            directed,
    
            addNode(key) {
                nodes.push(createNode(key))
            },
    
            getNode (key) {
                return nodes.find(n => n.key === key)
            },
    
            addEdge (node1Key, node2Key) {
                const node1 = this.getNode(node1Key);
                const node2 = this.getNode(node2Key);
    
                node1.addChild(node2);
    
                if (!directed) {
                    node2.addChild(node1);
                }
    
                edges.push(`${node1Key}${node2Key}`)
            },
    
            print() {
                return nodes.map(({children, key}) => {
                    let result = `${key}`;
    
                    if (children.length) {
                        result += ` => ${children.map(n => n.key).join(' ')}`
                    }
    
                    return result;
                }).join('
    ')
            }
        }
    }

    Run:

    const graph = createGraph(true)
    
    graph.addNode('Kyle')
    graph.addNode('Anna')
    graph.addNode('Krios')
    graph.addNode('Tali')
    
    graph.addEdge('Kyle', 'Anna')
    graph.addEdge('Anna', 'Kyle')
    graph.addEdge('Kyle', 'Krios')
    graph.addEdge('Kyle', 'Tali')
    graph.addEdge('Anna', 'Krios')
    graph.addEdge('Anna', 'Tali')
    graph.addEdge('Krios', 'Anna')
    graph.addEdge('Tali', 'Kyle')
    
    console.log(graph.print())
    
    /*
    Kyle => Anna Krios Tali
    Anna => Kyle Krios Tali
    Krios => Anna
    Tali => Kyle
    */
  • 相关阅读:
    图像和流媒体 -- 帧率、分辨率、码流的概念和关系(转)
    Linux设备驱动(转)
    STM32开发 -- 4G模块开发详解(转)
    Linux下EC20实现ppp拨号(转)
    使用机智云APP控制战舰V3 (转)
    USB Host读取U盘成功
    FreeModbus在STM32上移植(转)
    处理分页操作
    HBase参数配置及说明(转)
    学习JNDI
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10122411.html
Copyright © 2011-2022 走看看