Size of a graph using adjacency list versus adjacency matrix?

纵然是瞬间 提交于 2019-12-02 08:07:56

To answer your question, "What is the main difference between a list representation and matrix representation of a matrix?"

A list representation of a graph is usually a list of tuples, where each element of the list is a node, and the tuples are the nodes connected to it. Say we have 3 nodes A, B, C, so we will have a list of length 3. Say there is a node from A->B, then element in the Ath position, say the first element, will contain the node B. Say there is also a link from A->C, the first element will contain B and C. The total space required for an adjacency list is (space to represent a node) * (number of edges).

On the other hand, a matrix representation is a matrix, usually implemented as a 2-d array, where every node is listed on both the row and column axis. If there is a link between 2 nodes, then mark that spot in the matrix. For example, if we have 3 nodes A, B, C, we have a 3x3 array array. Let's call A=index 0, B=index 1, C=index 2, and suppose we have a link from A -> B, then fill in a 1 at array[0][1]. If our graph was undirected, we'd also add a 1 to the spot at array[1][0]. Total space required is the number of nodes N^2 times the space required by each link (can be done with 1 bit, 0 or 1), so total = N^2.

A list is good for sparse graphs because it doesn't require any extra storage. That is, links that don't exist aren't represented by anything. By contrast, if our graph is very dense, then a matrix representation is better because every possible link is denoted by only 1 bit (0 or 1). As you can see from the examples above, the total space required by a list representation is a function of the number of edges, while the space for a matrix representation is a function of the number of nodes.

Now think about your specific problem. How many total nodes would you have? Total edges? Does that seem sparse or dense?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!