Breadth First Search time complexity analysis

后端 未结 6 1589
说谎
说谎 2020-12-12 16:31

The time complexity to go over each adjacent edge of a vertex is, say, O(N), where N is number of adjacent edges. So, for V numbers of

6条回答
  •  没有蜡笔的小新
    2020-12-12 17:05

    The other answers here do a great job showing how BFS runs and how to analyze it. I wanted to revisit your original mathematical analysis to show where, specifically, your reasoning gives you a lower estimate than the true value.

    Your analysis goes like this:

    • Let N be the average number of edges incident to each node (N = E / V).
    • Each node, therefore, spends O(N) time doing operations on the queue.
    • Since there are V nodes, the total runtime is the O(V) · O(N) = O(V) · O(E / V) = O(E).

    You are very close to having the right estimate here. The question is where the missing V term comes from. The issue here is that, weirdly enough, you can't say that O(V) · O(E / V) = O(E).

    You are totally correct that the average work per node is O(E / V). That means that the total work done asympotically is bounded from above by some multiple of E / V. If we think about what BFS is actually doing, the work done per node probably looks more like c1 + c2E / V, since there's some baseline amount of work done per node (setting up loops, checking basic conditions, etc.), which is what's accounted for by the c1 term, plus some amount of work proportional to the number of edges visited (E / V, times the work done per edge). If we multiply this by V, we get that

    V · (c1 + c2E / V)

    = c1V + c2E

    = Θ(V + E)

    What's happening here is that those lovely lower-order terms that big-O so conveniently lets us ignore are actually important here, so we can't easily discard them. So that's mathematically at least what's going on.

    What's actually happening here is that no matter how many edges there are in the graph, there's some baseline amount of work you have to do for each node independently of those edges. That's the setup to do things like run the core if statements, set up local variables, etc.

提交回复
热议问题