What is time complexity of BFS depending on the representation of the graph?

后端 未结 4 1247
野性不改
野性不改 2021-02-04 15:15

I was wondering what is the time complexity of BFS, if I use:

  • an adjacency matrix
  • adjacency list
  • edge list

Is it same as their spa

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 15:24

    First let's look at the time complexity. If an adjacency matrix can be stored as a sparse matrix, the space complexity would be the same . A sparse matrix essentially stores only the nonzero values of the adjacency matrix, hence has the same space complexity as an adjacency list representation, i.e. O(|V| + |E|)

    Now on to time complexity. One way of doing a BFS search is to simply use a sparse adjacency matrix as one would normally use an adjacency list representation, i.e. O(|V| + |E|).

    Another way of doing a BFS on an adjacency matrix is by using sparse matrix-vector multiplications by repeatedly applying Y=G X, where G is a sparse adjacency matrix and X is a sparse vector with 1s on the frontier. This operation is basically a combination of columns of G. If this operation is implemented such that each multiplication takes time proportional to the size of the data accessed in each column of G and the number of nonzeros in the vector X, then the time complexity would also be O(|V| + |E|). An advantage of this approach is that it is straight forward to extend it to multiple BFS searches by replacing X with a sparse matrix representing the frontiers of several BFS searches. More details can be seen in this paper on implementations of graph algorithms using sparse matrices.

    An edge list is not typically used for BFS, since it is expensive to find the neighbors of a vertex.

提交回复
热议问题