Muscardinus

Undirected Graph 구현 본문

DataStructure

Undirected Graph 구현

Muscardinus 2020. 12. 13. 16:21
728x90
class Graph { 
  constructor() { 
    this.numberOfNodes = 0;
    this.adjacentList = {
    }; 
  } 
  addVertex(node)  { 
    if (!this.adjacentList[node]) {
      this.adjacentList[node] = [];
      this.numberOfNodes++;
    }
  } 
  addEdge(node1, node2) { 
    //undirected Graph
    if (!(this.adjacentList[node1] && this.adjacentList[node2])) return null;
    this.adjacentList[node1].push(node2);
    this.adjacentList[node2].push(node1);
  } 
  showConnections() { 
    const allNodes = Object.keys(this.adjacentList); 
    for (let node of allNodes) { 
      let nodeConnections = this.adjacentList[node]; 
      let connections = ""; 
      let vertex;
      for (vertex of nodeConnections) {
        connections += vertex + " ";
      } 
      console.log(node + "-->" + connections); 
    } 
} 
} 
728x90

'DataStructure' 카테고리의 다른 글

Binary Search Tree 구현  (0) 2020.12.13
Queue 구현  (0) 2020.12.12
Stack 구현  (0) 2020.12.12
Double Linked List 구현  (0) 2020.10.15
Linked List 구현  (0) 2020.10.15
Comments