Friday, 9 May 2014

DFS & BFS

Depth-First Search




procedure dfs(vertex v)
{
   mark v as visited
   for each w adjacent to v
      if w unvisited
         dfs(w)
}


Breadth-First Search

procedure BFS(vertex s)
{
   create a queue Q
   enqueue s onto Q
   mark s as visited
   while Q is not empty
   {
      dequeue a vertex from Q into v
      for each w adjacent to v
      {
         if w unvisited 
         {
            mark w as visited
            enqueue w onto Q
         }
      }
   }
}


DFS
BFS

No comments:

Post a Comment