7.4. 邻接矩阵¶
7.4. An Adjacency Matrix
实现图的一种最简单方法是使用二维矩阵。在这种矩阵实现中,每一行和每一列都表示图中的一个顶点。存储在行 Figure 3
说明了 Figure 2
图的邻接矩阵。每个单元格中的值表示从顶点

邻接矩阵的优点是它简单,对于小型图,易于查看哪些节点连接到其他节点。然而,注意到矩阵中的大多数单元格是空的;我们可以说这个矩阵是 稀疏的。矩阵不是存储稀疏数据的高效方式。实际上,在 Python 中,你必须特别创建像 Figure 3
中的矩阵结构。
邻接矩阵在边的数量很大时是图的一个很好的实现。但什么是“很大”?填满矩阵需要多少条边?由于图中每个顶点都有一行和一列,因此填满矩阵所需的边数是
One of the easiest ways to implement a graph is to use a two-dimensional matrix. In this matrix implementation, each of the rows and columns represents a vertex in the graph. The value that is stored in the cell at the intersection of row Figure 3
illustrates the adjacency matrix for the graph in Figure 2
. The value in each cell represents the weight of the edge from vertex

The advantage of the adjacency matrix is that it is simple, and for small graphs it is easy to see which nodes are connected to other nodes. However, otice that most of the cells in the matrix are empty; we can say that this matrix is sparse. A matrix is not a very efficient way to store sparse data. In fact, in Python you must go out of your way to even create a matrix structure like the one in Figure 3
.
The adjacency matrix is a good implementation for a graph when the number of edges is large. But what do we mean by large? How many edges would be needed to fill the matrix? Since there is one row and one column for every vertex in the graph, the number of edges required to fill the matrix is
创建日期: 2024年9月9日