Reputation: 323
I have an algorithm to find the edges of a directed graph from a vertex u to any other vertex which has a O(|V|+|E|) time complexity (based on DFS). I have to develop an algorithm to find the edges between any two vertex u and v in O(|V||E|).
Do you have any suggestions or hints to achieve this?
If I repeat the DFS-Visit for every vertex, only the first time the vertex are white and the following times the call will do nothing. If I reset the colour before do that, then the algorithm will be O(|V|^2 + |V||E|).
Thanks you so much in advance!
Upvotes: 3
Views: 695
Reputation: 178511
Split the problem into sub-problems where you can use your algorithm to achieve the required complexity, as follows:
The complexity will be:
Step 1 is O(V+E)
- DFS.
Step 2:
i
the complexity is O(V_i^2 + V_i*E_i)
i
: E_i >= V_i -1
(otherwise it was not
connected, a tree has |V|-1
edges), O(ViEi + Vi^2) = O(ViEi)
.O(V1E1 + V2E2 + ... + VkEk)
.Note that for each i
E_i <= E
, and thus the complexity is not
worse then:
O(V1E + V2E + ... + VkE) = O(E *(V1+V2+ ... + Vk)) = O(VE)
Thus, the total complexity is O(VE)
, as required.
Upvotes: 3