iT邦幫忙

2021 iThome 鐵人賽

DAY 20
1

圖(Graph)建立的方法

  • addVertex: 新增頂點
  • addEdge: 新增邊
  • removeVertex: 刪除頂點
  • removeEdge: 刪除邊

圖的介紹可以參考此篇


JavaScript

  • 無向圖
  • 相鄰串列 (Adjacency List)
class Graph {
  constructor() {
    this.adjacencyList = {}
  }

  //新增頂點
  addVertex(vertex) {
    if (!this.adjacencyList[vertex]) {
      this.adjacencyList[vertex] = []
    } else {
      return '頂點已存在';
    }
  }
  
  //新增邊
  addEdge(vertex1, vertex2) {
    if (this.adjacencyList[vertex1]) {
      if (this.adjacencyList[vertex2]){
        this.adjacencyList[vertex1].push(vertex2)
        this.adjacencyList[vertex2].push(vertex1)
      }else {
        return '第二項頂點不存在';
      }
    } else {
      return '第一項頂點不存在';
    }
  }
  
  //刪除頂點
  removeVertex(vertex) {
    if (this.adjacencyList[vertex]) {
      this.adjacencyList[vertex].forEach(function(item) {
        this.removeEdge(vertex, item)
        delete this.adjacencyList[vertex]
      });
    } else {
      return '此頂點已不存在';
    }
  }
  
  //刪除邊
  removeEdge(vertex1, vertex2) {
    if (this.adjacencyList[vertex1]) {
      if (this.adjacencyList[vertex2]){
        this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(
          (vertex) => vertex !== vertex2
        )
        this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(
          (vertex) => vertex !== vertex1
        )
      }else {
        return '第二項頂點已不存在';
      }
    } else {
      return '第一項頂點已不存在';
    }
  }

  printGraph(){
    console.log(this.adjacencyList)
  }

}

let graph = new Graph();

graph.addVertex('A');
graph.addVertex('B');
graph.addVertex('C');
graph.addVertex('D');
graph.addVertex('E');
graph.addVertex('F');

graph.addEdge('A', 'B');
graph.addEdge('A', 'D');
graph.addEdge('A', 'E');
graph.addEdge('B', 'C');
graph.addEdge('D', 'E');
graph.addEdge('E', 'F');
graph.addEdge('E', 'C');
graph.printGraph();
//{
//  A: ["B", "D", "E"],
//  B: ["A", "C"],
//  C: ["B", "E"],
//  D: ["A", "E"],
//  E: ["A", "D", "F", "C"],
//  F: ["E"]
//}

https://ithelp.ithome.com.tw/upload/images/20211001/20121027CE7B6iEvM0.jpg


Python

  • 無向圖
  • 使用Numpy實作相鄰矩陣(Adjacency Matrix)
import numpy as np
 
vertices = {0, 1, 2, 3, 4}
edges = {(0, 1), (1, 2), (0, 3), (1, 3), (3, 4)}
adjacencyMatrix = np.zeros((5, 5)).astype(int)
for edge in edges:
    v1 = edge[0]
    v2 = edge[1]
    adjacencyMatrix[v1][v2] = 1
    adjacencyMatrix[v2][v1] = 1
print("Vertices:",vertices)
print("Edges:",edges)
print(adjacencyMatrix)
#Vertices: {0, 1, 2, 3, 4}
#Edges: {(0, 1), (1, 2), (1, 3), (0, 3), (3, 4)}
#[[0 1 0 1 0]
# [1 0 1 1 0]
# [0 1 0 0 0]
# [1 1 0 0 1]
# [0 0 0 1 0]]

https://ithelp.ithome.com.tw/upload/images/20211001/20121027LrGXUEJeNB.jpg


上一篇
【Day19】[資料結構]-圖Graph
下一篇
【Day21】[演算法]-排序Sort & 氣泡排序法Bubble Sort
系列文
資料結構與演算法,使用JavaScript與Python35
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言