数据结构和算法

数据结构 — 图

2022-05-29  本文已影响0人  lio_zero

(graph)是一种数据结构,由一组节点或顶点以及一组表示这些节点之间连接的边组成。图可以是有向的或无向的,而它们的边可以分配数字权重。

JavaScript 图可视化

图数据结构中的每个节点都必须具有以下属性:

图数据结构中的每条边都必须具有以下属性:

图数据结构的主要操作有:

JavaScript 实现

class Graph {
  constructor(directed = true) {
    this.directed = directed
    this.nodes = []
    this.edges = new Map()
  }

  addNode(key, value = key) {
    this.nodes.push({ key, value })
  }

  addEdge(a, b, weight) {
    this.edges.set(JSON.stringify([a, b]), { a, b, weight })
    if (!this.directed) this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight })
  }

  removeNode(key) {
    this.nodes = this.nodes.filter(n => n.key !== key)
    ;[...this.edges.values()].forEach(({ a, b }) => {
      if (a === key || b === key) this.edges.delete(JSON.stringify([a, b]))
    })
  }

  removeEdge(a, b) {
    this.edges.delete(JSON.stringify([a, b]))
    if (!this.directed) this.edges.delete(JSON.stringify([b, a]))
  }

  findNode(key) {
    return this.nodes.find(x => x.key === key)
  }

  hasEdge(a, b) {
    return this.edges.has(JSON.stringify([a, b]))
  }

  setEdgeWeight(a, b, weight) {
    this.edges.set(JSON.stringify([a, b]), { a, b, weight })
    if (!this.directed) this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight })
  }

  getEdgeWeight(a, b) {
    return this.edges.get(JSON.stringify([a, b])).weight
  }

  adjacent(key) {
    return [...this.edges.values()].reduce((acc, { a, b }) => {
      if (a === key) acc.push(b)
      return acc
    }, [])
  }

  indegree(key) {
    return [...this.edges.values()].reduce((acc, { a, b }) => {
      if (b === key) acc++
      return acc
    }, 0)
  }

  outdegree(key) {
    return [...this.edges.values()].reduce((acc, { a, b }) => {
      if (a === key) acc++
      return acc
    }, 0)
  }
}
const g = new Graph()

g.addNode('a')
g.addNode('b')
g.addNode('c')
g.addNode('d')

g.addEdge('a', 'c')
g.addEdge('b', 'c')
g.addEdge('c', 'b')
g.addEdge('d', 'a')

g.nodes.map(x => x.value) // ['a', 'b', 'c', 'd']
;[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`)
// ['a => c', 'b => c', 'c => b', 'd => a']

g.adjacent('c') // ['b']

g.indegree('c') // 2
g.outdegree('c') // 1

g.hasEdge('d', 'a') // true
g.hasEdge('a', 'd') // false

g.removeEdge('c', 'b')
;[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`)
// ['a => c', 'b => c', 'd => a']

g.removeNode('c')

g.nodes.map(x => x.value) // ['a', 'b', 'd']
;[...g.edges.values()].map(({ a, b }) => `${a} => ${b}`)
// ['d => a']

g.setEdgeWeight('d', 'a', 5)
g.getEdgeWeight('d', 'a') // 5

以上内容译自 30 seconds of code 的 JavaScript Data Structures - Graph

更多资料

Graph (both directed and undirected)

上一篇下一篇

猜你喜欢

热点阅读