用Javascript实现图形

时间:2019-01-28 17:09:52

标签: javascript graph

这是我的图形实现,

class Graph {
  constructor(directed = false) {
    this.numVertices = 0;
    this.directed = directed;
    this.dict = {}
  }

  addEdge(v1, v2, weight) {
    let p, q;
    if (v1 in this.dict) {
      p = this.dict[v1];
    } else {
      p = new Node(v1);
      this.dict[v1] = p;
      this.numVertices++;
    }
    if (v2 in this.dict) {
      q = this.dict[v2];
    } else {
      q = new Node(v2);
      this.dict[v2] = q;
      this.numVertices++;
    }
    p.addEdge(q);
  }
  stringify() {
    for (const [key, value] of Object.entries(this.dict)) {
      console.log(`${key}: ${value.adjacencySet}`);
    }
  }
}

// This is the node class.
class Node {
  constructor(data) {
    this.data = data;
    this.adjacencySet = new Set();
  }
  addEdge(node) {
    this.adjacencySet.add(node)
  }
  getAdjacentVertices() {
    return this.adjacencySet;
  }
}

// This is the calling client I'm using.
graph = new Graph();
graph.addEdge(12, 13);
graph.addEdge(12, 14);
graph.addEdge(13, 15);
graph.addEdge(14, 6);
graph.stringify();

运行此命令时,得到的图形表示为

6: [object Set]
12: [object Set]
13: [object Set]
14: [object Set]
15: [object Set]

理想情况下,我想在邻接表的每个元素中打印节点的值。 如何在节点中打印数据。

1 个答案:

答案 0 :(得分:1)

您可以将集合转换为数组,然后将节点映射到它们的值。

[...value.adjacencySet].map(x => x.data)

class Graph {
  constructor(directed = false) {
    this.numVertices = 0;
    this.directed = directed;
    this.dict = {}
  }

  addEdge(v1, v2, weight) {
    let p, q;
    if (v1 in this.dict) {
      p = this.dict[v1];
    } else {
      p = new Node(v1);
      this.dict[v1] = p;
      this.numVertices++;
    }
    if (v2 in this.dict) {
      q = this.dict[v2];
    } else {
      q = new Node(v2);
      this.dict[v2] = q;
      this.numVertices++;
    }
    p.addEdge(q);
  }
  stringify() {
    for (const [key, value] of Object.entries(this.dict)) {
      console.log(`${key}: ${[...value.adjacencySet].map(x => x.data)}`);
    }
  }
}

// This is the node class.
class Node {
  constructor(data) {
    this.data = data;
    this.adjacencySet = new Set();
  }
  addEdge(node) {
    this.adjacencySet.add(node)
  }
  getAdjacentVertices() {
    return this.adjacencySet;
  }
}

// This is the calling client I'm using.
graph = new Graph();
graph.addEdge(12, 13);
graph.addEdge(12, 14);
graph.addEdge(13, 15);
graph.addEdge(14, 6);
graph.stringify();