首页 技术 正文
技术 2022年11月21日
0 收藏 566 点赞 3,922 浏览 1437 个字

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
*/
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,941
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,465
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,280
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,094
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,728
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,765