Graph Representations 1 Graph Representation B 2 4
Graph Representations 1
Graph Representation B 2 4 3 7 A C 2 F 7 3 1 D 6 E 6 z. How can I represent the above graph? 2
Pointer Representation A 2 1 B 4 3 7 3 C 6 D 7 E 2 F 6 z. Idea: each vertex is an instance of a class with a linked list of vertices representing the edges. z. Thus, “A” would be an instance having a linked list consisting of “B” and “C”. 3
Pointer Representation A 2 1 B 4 3 7 3 C 6 D 7 E 2 F 6 z. Problem: unlike Binary Search Trees, Graphs have no “root” and thus no single logical place to begin access. z. I need to be able to access the graph starting from any vertex. 4
Adjacency Lists A 2 1 B 4 3 7 3 C 6 D 7 E 2 F 6 z. Better idea: maintain each vertex as an element of a linked list. z. Each element of the linked list has a pointer to a linked list of adjacent vertices: 5
Adjacency Lists A A B 2 C 1 2 1 B 4 3 7 3 C B A 2 D 3 E 4 F 7 C A 1 D 3 E 6 F 6 D B 3 C 3 F 2 E B 2 C 6 F B 7 C 7 D 2 6 D 7 E 2 F 6 E 6 6
Adjacency List Discussion z. Each vertex is located by following the blue edges. z. Edges are represented by the black edges: the source vertex is the current vertex in the blue list, the destination is the edge in the edge list (the label is also present, if needed). z. How much time does it take to determine if there is an edge from vertex X to Y? 7
Adjacency Matrix Representation z. Another idea is, if you know how many edges you have, store the graph in an n×n array. Element [i, j] stores the label of the edge from vertex i to vertex j (or 0/NULL if no such edge exists). 8
Adjacency Matrix Example 2 B 4 A 1 A A B C 2 1 3 7 3 C 6 D E F B 2 3 4 7 C 1 3 6 7 D 3 3 2 E 4 6 6 F 7 7 2 D 7 E 2 F 6 6 9
Adjacency Matrix Discussion z. How much time does it take to determine if there is an edge from vertex X to Y? 10
The End Slide z 11
- Slides: 11