iT邦幫忙

2023 iThome 鐵人賽

DAY 16
0
自我挑戰組

資料結構與演算法-CS61B學習筆記系列 第 16

Day16-Graph Implementation

  • 分享至 

  • xImage
  •  

這章節要來點hardcore的,就是分析graph traversal的runtime。要做到這件事分3個步驟:

1.Graph API
2.Graph implementation data structure
3.DepthFirstPaths & BreadthFirstPaths implementation

1.Graph API:

public class Graph{
    public Graph(int V); // Create empty graph with v vertices.
    public void addEdge(int v, int w); // add an edge v-w.
    Iterable<Integer> adj(int v); // vertices adjacent to v.
    int V(); // number of vertices.
    int E(); // number of edges.
}
  • Number of vertices must be specified in advance.
  • Does not support weights(labels) on nodes or edges.
  • Has no method for getting the number of edges for a vertex (i.e. its degree).

2.Graph implementation data structure

i. adjacency matrix

01

ii. edge sets

02

iii. adjacency lists

03

各個implementation的runtime比較:

以print()來說,目標是印出所有的連結關係,所以code會長這樣:

void print(Graph G){
    for(v = 0; v < G.V(); v++){
        for(int w : G.adj(v)){
            System.out.println(v + "-" + w);
        }
    }
}

所以若Graph的資料結構使用adjacency matrix的話,就會是Θ(V^2);而若使用adjacency list就會是Θ(V+E):

04

由此可知adjacency list的效能比較好,這也剛好是Graph最常見的實作資料結構。

Graph implementation in adjacency lists:

05

3.DepthFirstPaths & BreadthFirstPaths implementation

i. DepthFirstPaths

06

ii. BreadthFirstPaths

07

Runtime of different Graph implementation:

08

09

可以看到,Graph內部的實作細節可以大幅度的影響到DFS & BFS的效能!

Slides are from Josh Hug CS61B
license
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License


上一篇
Day15-Graph traversal - BreadthFirstSearch
下一篇
Day17-Graph traversal - s-t path (Dijkstra)
系列文
資料結構與演算法-CS61B學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言