BFS时间复杂度问题

来源:互联网 发布:网络招聘平台对比 编辑:程序博客网 时间:2024/05/21 08:29

BFS(s):


Set Discovered[s] = true and Discovered[v] = false for all other vInitialize L[0] to consist of the single element sSet the layer counter i = 0Set the current BFS tree T =∅While L[i] is not empty    Initialize an empty list L[i + 1]    For each node u ∈ L[i]        Consider each edge (u, v) incident to u        If Discovered[v] = false then            Set Discovered[v] = true            Add edge (u, v) to the tree T            Add v to the list L[i + 1]         Endif    Endfor    Increment the layer counter i by oneEndwhile



解: 最多有n个list需要set up,所以这个是O(n) time。每进一次while,for走的都是与u相连的edge的数量 + set下一个list, 算下来走完算法是O(m+n)。

0 0
原创粉丝点击