Generic Graph
Last updated
Last updated
In this section, I will only introduce the data structure of generic graph and the implementation. The more complex version of graph is in the following chapter.
Let's back to this straightforward staff: The adjacency matrix to describing or saving a graph in the memory. If node A and node B is interconnected, then adj[A][B] = adj[B][A] = edge_value
(Where edge_value (边权值)
is the cost of travelling through each edges). If it is a directed graph, A -> B
means there is a path from A to B but not from B to A, then adj[A][B] = edge_value
. The space complexity is $O(N^2)$. That means if the graph has 1,000,000 nodes, an 1,000,000 x 1,000,000 matrix will take in use. Although the size is horrible, it is the most easy understanding way of describing a graph, here is the example and code implementation.
Code to initialize
Exercise: Build an adjacency matrix of non-directed graph in last figure then print the matrix and list all the edge in A --- B
form.
One of the solutions
An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an G[]
. An entry G[i]
represents the list of vertices adjacent to the i-th vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Following is the adjacency list representation. It is not hard to change the adjacency matrix to list form if you really understand how it works.
Code to implement [src code]
Up till now, you have read all of the contents of Chapter 1. I strongly advice you writing the code from the scratch to implement the basic data structure. In the following chapter, it's time to learn some tricky stuffs.