Chapter 36: Graphs

前言

圖是由點跟邊所構成的。本章介紹兩種不同方式來組成graph。

大綱

  • Weighted graphs

    • Directed graphs

    • Undirected graphs

  • Common operations

  • Defining a vertex

  • Defining an edge

  • Adjacency list

    • Implementation

      • Creating a vertex

      • Creating a directed edge

      • Creating an undirected edge

      • Retrieving the outgoing edges from a vertex

      • Retrieving the weight of an edge

      • Visualizing the adjacency list

      • Building a network

  • Adjacency matrix

    • Implementation

      • Creating a Vertex

      • Creating edges

      • Retrieving the outgoing edges from a vertex

      • Retrieving the weight of an edge

      • Visualize an adjacency matrix

      • Building a network

  • Graph analysis

Weighted graphs

  • 邊具有權重

Directed graphs: 邊具有方向性

Undirected graphs: 無向邊可以看成雙向的意思

Common operations

常見的操作

  • 加入點

  • 加入方向邊

  • 加入無向邊

  • 取得於某個點相連的所有邊

  • 取得某兩點之間邊的權重

Defining a vertex

  • A vertex has a unique index within its graph and holds a piece of data

  • The Hashable protocol inherits from Equatable, so you must also satisfy this protocol's requirement. The compiler can synthesize conformance to both protocols, which is why the extensions above are empty.

Defining an edge

  • 邊可能具有權重,並且連接兩個點

Adjacency list

  • Init

  • Creating a vertex

  • Creating a directed edge

  • Creating an undirected edge

  • Retrieving the outgoing edges from a vertex

  • Retrieving the weight of an edge

Adjacency matrix

  • Init

  • Creating a Vertex

  • Creating edges

  • Retrieving the outgoing edges from a vertex

  • Retrieving the weight of an edge

Graph analysis

  • If there are few edges in your graph, it is considered a sparse graph, and an adjacency list would be a good fit.

  • If your graph has lots of edges, it’s considered a dense graph, and an adjacency matrix would be a better fit as you’d be able to access your weights and edges far more quickly.

Last updated