Why does the time complexity of DFS and BFS depend on the way the graph is represented?

后端 未结 3 1431
予麋鹿
予麋鹿 2021-01-30 14:46

The site http://web.eecs.utk.edu/~huangj/CS302S04/notes/graph-searching.html describes that when an adjacency list is used then, DFS and BFS have complexity O(V+E), and if an ad

3条回答
  •  粉色の甜心
    2021-01-30 15:12

    In both cases, the runtime depends on how long it takes to iterate across the outgoing edges of a given node. With an adjacency list, the runtime is directly proportional to the number of outgoing edges. Since each node is visited once, the cost is the number of nodes plus the number of edges, which is O(m + n). With am adjacency matrix, the time required to find all outgoing edges is O(n) because all n columns in the row for a node must be inspected. Summing up across all n nodes, this works out to O(n2).

    Hope this helps!

提交回复
热议问题