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

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

    Lets assume we have a graph which has n number of nodes and m number of edges,

    Example graph

    Adjacency Matrix: We are creating a matrix that has n number of rows and columns so in memory it will take space that is proportional to n2. Checking if two nodes named as u and v has an edge between them will take Θ(1) time. For example checking for (1, 2) is an edge will look like as follows in the code:

    if(matrix[1][2] == 1)
    

    If you want to identify all edges, you have to iterate over matrix at this will require two nested loops and it will take Θ(n2). (You may just use the upper triangular part of the matrix to determine all edges but it will be again Θ(n2))

    Adjacency List: We are creating a list that each node also points to another list. Your list will have n elements and each element will point to a list that has number of items that is equal to number of neighbors of this node (look image for better visualization). So it will take space in memory that is proportional to n+m. Checking if (u, v) is an edge will take O(deg(u)) time in which deg(u) equals number of neighbors of u. Because at most, you have to iterate over the list that is pointed by the u. Identifying all edges will take Θ(n+m).

    Adjacency list of example graph


    You should make your choice according to your needs. Because of my reputation I couldn't put image of matrix, sorry for that

提交回复
热议问题