What is better, adjacency lists or adjacency matrices for graph problems in C++?

后端 未结 11 1101
小鲜肉
小鲜肉 2020-11-28 00:41

What is better, adjacency lists or adjacency matrix, for graph problems in C++? What are the advantages and disadvantages of each?

11条回答
  •  鱼传尺愫
    2020-11-28 01:38

    It depends on what you're looking for.

    With adjacency matrices you can answer fast to questions regarding if a specific edge between two vertices belongs to the graph, and you can also have quick insertions and deletions of edges. The downside is that you have to use excessive space, especially for graphs with many vertices, which is very inefficient especially if your graph is sparse.

    On the other hand, with adjacency lists it is harder to check whether a given edge is in a graph, because you have to search through the appropriate list to find the edge, but they are more space efficient.

    Generally though, adjacency lists are the right data structure for most applications of graphs.

提交回复
热议问题