[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('\n')
        }
    }
}
复制代码

 

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
*/
复制代码

 

posted @   Zhentiw  阅读(281)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-12-15 [Python] Read and plot data from csv file
2017-12-15 [React] Make Controlled React Components with Control Props
2016-12-15 [JS Compose] 6. Semigroup examples
2016-12-15 [JS Compose] 5. Create types with Semigroups
2014-12-15 [AngularJS] $http cache
2014-12-15 [AngularJS+ GSAP] Greensock TimelineLite Animation Sequences
点击右上角即可分享
微信分享提示