[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 */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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