Sei sulla pagina 1di 1

DFS & Find a cycle

Algorithm Depth_first_Search (G, v); Input: G=(V,E) (an undirected connected graph), and v (a vertex og G); Output: Begin Mark v; Per or! pre"ork on v; #pre"ork depend$ on the appication o %&'( &or a)) edge$ (v,w) do I w i$ un!arked then %epth* ir$t*'earch (G, w); Per or! post"ork or (v,w); #po$t"ork depend$ on the app)ication o %&'; it i$ $o!eti!e$ per or!ed on)+ on edge$ )eading to ne")+ !arked vertice$;( End Algorithm Find_a_Cycle (G,v); Input: G=(V,E) (an directed graph), Output: &ind*a*-+)c)e (tr e if G contains a cycle and a)$e other"i$e), Begin Mark v; v,on*the*path:=true; ..pre"ork #x,on*the*path i$ true i x i$ on the path ro! the root to current vertex( #initia))+ x,on*the*path:= a)$e or a)) vertice$, and &ind*a*-+c)e i$ a)$e( &or a)) edge$ (v,w) do I w i$ un!arked then &ind*a*-+c)e (G, w); I w,on*the*path then &ind*a*-+c)e:=tr e; ha)t; ..po$t"ork I w i$ the )a$t vertex on v$ )i$t then v,on*the*path:=false; ..po$t"ork End /)gorith! Connected_components (G); Input: G=(V,E) (an undirected graph), Output: v!component i$ $et the n m"er o the co!ponent containing v; or ever+ vertex v, Begin -o!ponent*0u!1er:=2; 3hi)e there i$ an un!arked vertex v do %epth*&ir$t*'earch (G,v); (u$ing the o))o"ing pre"ork: v!Component#$Component_% m"er;) -o!ponent*0u!1er:= -o!ponent*0u!1er42; end

Potrebbero piacerti anche