Professional Documents
Culture Documents
Depth-First Search (DFS) For Undirected Graphs - Graph Theory - Algorithms and Data Structures
Depth-First Search (DFS) For Undirected Graphs - Graph Theory - Algorithms and Data Structures
Depth-first search (DFS) for undirected graphs :: Graph theory | Algorithms and Data Structures
AlgorithmsandDataStructures
withimplementationsinJavaandC++
Datastructures
Needhelpwithaprogrammingassignment?Getaffordableprogramminghomeworkhelp.
Algorithms
Depthfirstsearch(DFS)forundirectedgraphs
C++
Books
Depthfirstsearch,orDFS,isawaytotraversethegraph.Initiallyitallowsvisitingverticesofthegraphonly,
buttherearehundredsofalgorithmsforgraphs,whicharebasedonDFS.Therefore,understandingtheprinciples
ofdepthfirstsearchisquiteimportanttomoveaheadintothegraphtheory.Theprincipleofthealgorithmisquite
simple:togoforward(indepth)whilethereissuchpossibility,otherwisetobacktrack.
Forum
Feedback
Algorithm
C++codesnippets
EconomicsTextbook
InDFS,eachvertexhasthreepossiblecolorsrepresentingitsstate:
white:vertexisunvisited
Supportus
gray:vertexisinprogress
towrite
moretutorials
black:DFShasfinishedprocessingthevertex.
NB.For most algorithms boolean classification unvisited / visited is quite enough, but we show general case
here.
tocreatenew
visualizers
Initiallyallverticesarewhite(unvisited).DFSstartsinarbitraryvertexandrunsasfollows:
1. Markvertexuasgray(visited).
2. Foreachedge(u,v),whereuiswhite,rundepthfirstsearchforurecursively.
3. Markvertexuasblackandbacktracktotheparent.
Example.Traverseagraphshownbelow,usingDFS.Startfromavertexwithnumber1.
tokeepsharing
freeknowledge
foryou
everydollarhelps
Sourcegraph.
TOP3Articles
Quicksort
Depthfirstsearch
Binarysearchtree
Markavertex1asgray.
http://www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search
1/7
12/27/2014
Depth-first search (DFS) for undirected graphs :: Graph theory | Algorithms and Data Structures
Thereisanedge(1,4)andavertex4isunvisited.Go
there.
Markthevertex4asgray.
Thereisanedge(4,2)andvertexa2isunvisited.Go
there.
Markthevertex2asgray.
Thereisanedge(2,5)andavertex5isunvisited.Go
there.
http://www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search
2/7
12/27/2014
Depth-first search (DFS) for undirected graphs :: Graph theory | Algorithms and Data Structures
Markthevertex5asgray.
Thereisanedge(5,3)andavertex3isunvisited.Go
there.
Markthevertex3asgray.
Therearenowaystogofromthevertex3.Markitas
blackandbacktracktothevertex5.
Thereisanedge(5,4),butthevertex4isgray.
http://www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search
3/7
12/27/2014
Depth-first search (DFS) for undirected graphs :: Graph theory | Algorithms and Data Structures
Therearenowaystogofromthevertex5.Markitas
blackandbacktracktothevertex2.
Therearenomoreedges,adjacenttovertex2.Markitas
blackandbacktracktothevertex4.
Thereisanedge(4,5),butthevertex5isblack.
Therearenomoreedges,adjacenttothevertex4.Markit
asblackandbacktracktothevertex1.
http://www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search
4/7
12/27/2014
Depth-first search (DFS) for undirected graphs :: Graph theory | Algorithms and Data Structures
Therearenomoreedges,adjacenttothevertex1.Markit
asblack.DFSisover.
Asyoucanseefromtheexample,DFSdoesn'tgothroughalledges.Theverticesandedges,whichdepthfirst
searchhasvisitedisatree.Thistreecontainsallverticesofthegraph(ifitisconnected)andiscalledgraph
spanningtree.ThistreeexactlycorrespondstotherecursivecallsofDFS.
If a graph is disconnected, DFS won't visit all of its vertices. For details, see finding connected components
algorithm.
Complexityanalysis
Assumethatgraphisconnected.Depthfirstsearchvisitseveryvertexinthegraphandcheckseveryedgeits
edge.Therefore,DFScomplexityisO(V+E).Asitwasmentionedbefore,ifanadjacencymatrixisusedfor
a graph representation, then all edges, adjacent to a vertex can't be found efficiently, that results in O(V2)
complexity.YoucanfindstrongproofoftheDFScomplexityissuesin[1].
Codesnippets
Intruththeimplementationstatedbelowgivesnoyields.YouwillfillanactualuseofDFSinfurthertutorials.
Java
publicclassGraph{
enumVertexState{
White,Gray,Black
}
publicvoidDFS()
{
VertexStatestate[]=newVertexState[vertexCount]
for(inti=0i<vertexCounti++)
state[i]=VertexState.White
runDFS(0,state)
}
publicvoidrunDFS(intu,VertexState[]state)
{
state[u]=VertexState.Gray
for(intv=0v<vertexCountv++)
if(isEdge(u,v)&&state[v]==VertexState.White)
runDFS(v,state)
state[u]=VertexState.Black
}
}
C++
enumVertexState{White,Gray,Black}
http://www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search
5/7
12/27/2014
Depth-first search (DFS) for undirected graphs :: Graph theory | Algorithms and Data Structures
voidGraph::DFS(){
VertexState*state=newVertexState[vertexCount]
for(inti=0i<vertexCounti++)
state[i]=White
runDFS(0,state)
delete[]state
}
voidGraph::runDFS(intu,VertexStatestate[]){
state[u]=Gray
for(intv=0v<vertexCountv++)
if(isEdge(u,v)&&state[v]==White)
runDFS(v,state)
state[u]=Black
}
Visualizers
1. GraphTraversalinJavaAppletsCentre
Recommendedbooks
1. Cormen,Leiserson,Rivest.Introductiontoalgorithms.(Theory)
2. Aho,Ullman,Hopcroft.DataStructuresandAlgorithms.(Theory)
3. RobertLafore.DataStructuresandAlgorithmsinJava.(Practice)
4. MarkAllenWeiss.DataStructuresandProblemSolvingUsingC++.(Practice)
Threeresponsesto"Depthfirstsearch(DFS)forundirectedgraphstutorial"
1. ajonApril9,2009said:
tutorialissogood,interactiveandeasytounderstand
2. LeToanonApril8,2009said:
thankyouverymuchaboutDFS
3. elahehonMar28,2009said:
itwasreallygreatthanks
Like 77peoplelikethis.Bethefirstofyourfriends.
ContributetoAlgoList
Likedthistutorial?Please,considermakingadonation.Contributetohelpuskeepsharingfreeknowledgeand
writenewtutorials.
Everydollarhelps!
Partners
GetCheapInternet
Leaveareply
Yourname(optional):
Youremail(optional):
Message:
http://www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search
6/7
12/27/2014
Depth-first search (DFS) for undirected graphs :: Graph theory | Algorithms and Data Structures
Send
http://www.algolist.net/Algorithms/Graph/Undirected/Depth-first_search
7/7