0

I've got a minimum spanning tree. I add an edge to it. Surely a cycle is formed. I need to find all the edges that are part of that cycle ie., all the back edges. How quickly can that be done? My solution- For example if it's edge (1,4), add 4 to Adj(1) at all places and run dfs every time. Eg. if Adj(1) had 2,3,5, first add 4 before 2, run DFS. I'll get a back edge. Then add 4 between 2 and 3 and run dfs. I get the another back edge. Then between 3 and 5 and so on. Is there any faster way to do this?

aandis
  • 4,084
  • 4
  • 29
  • 40

2 Answers2

3

In a tree you have a single (simple) route between any pair of vertices. If you are adding an edge (i,j), first find the route in the tree between i and j and then you will have your cycle - it consists of all the vertices in that route(and turns into a cycle once you add (i,j) as edge).

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
  • and I think a dfs will suffice for that. – aandis Dec 09 '13 at 13:31
  • Any type of search will do for finding the single path between a pair of vertices in a tree. BFS, DFS or any other correct search. – Ivaylo Strandjev Dec 09 '13 at 13:33
  • I created my adjacency list a different way and was looking at that the whole time. So this didn't just pop in my mind! This was easy man! Thanks! :) – aandis Dec 09 '13 at 13:33
0

You are looking for the strongly connected components of the graph, which can be found using Tarjan's algorithm (among others).

Andy Jones
  • 4,723
  • 2
  • 19
  • 24
  • I don't think strongly connected components will help here. The question is a bit cryptic but OP is simply looking to find the cycle formed by adding an edge to a tree(if I understand it correctly) – Ivaylo Strandjev Dec 09 '13 at 13:16
  • If there's a single cycle in the tree, the strongly connected component of the graph will be exactly that cycle. – Andy Jones Dec 09 '13 at 13:17
  • It is hard to define the term strongly connected component for an undirected graph. What do you mean? – Ivaylo Strandjev Dec 09 '13 at 13:18
  • Ah rats, missed the "undirected" part of the title. The tree I had in my mind was one where each parent has a pointer to each of it's children. – Andy Jones Dec 09 '13 at 13:21
  • Strongly connected components are defined only for directed graphs I think. – aandis Dec 09 '13 at 13:24