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

后端 未结 11 1103
小鲜肉
小鲜肉 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:33

    It depends on the problem.

    Adjacency Matrix

    • Uses O(n^2) memory
    • It is fast to lookup and check for presence or absence of a specific edge
      between any two nodes O(1)
    • It is slow to iterate over all edges
    • It is slow to add/delete a node; a complex operation O(n^2)
    • It is fast to add a new edge O(1)

    Adjacency List

    • Memory usage depends on the number of edges (not number of nodes),
      which might save a lot of memory if the adjacency matrix is sparse
    • Finding the presence or absence of specific edge between any two nodes
      is slightly slower than with the matrix O(k); where k is the number of neighbors nodes
    • It is fast to iterate over all edges because you can access any node neighbors directly
    • It is fast to add/delete a node; easier than the matrix representation
    • It fast to add a new edge O(1)

提交回复
热议问题