"No one is harder on a talented person than the person themselves" - Linda Wilkinson ; "Trust your guts and don't follow the herd" ; "Validate direction not destination" ;

December 21, 2009

DFS Vs BFS

Depth First Search Vs Breadth First Search
DFS
  • A depth-first search (DFS) explores a path all the way to a leaf before backtracking and exploring another path
  • For example, after searching A, then B, then D, the search backtracks and tries another path from B
  • Node are explored in the order A B D E H L M N I O P C F G J K Q
  • N will be found before J  

DFS -
  • Takes less memory
  • The disadvantages are that it takes longer, and will not always find the shortest path
  • Can get struck if Tree has loops
 BFS
  • A breadth-first search (BFS) explores nodes nearest the root before exploring nodes further away
  • For example, after searching A, then B, then C, the search proceeds with D, E, F, G
  • Node are explored in the order A B C D E F G H I J K L M N O P Q
  • J will be found before N 

BFS
  • Will Always find shortest path
  • Can Deal with Looping Structures
  • Takes lot of memory
Algorithm - Pseudo Code
Depth-first searching:

Put the root node on a stack;
while (stack is not empty)
                       {
                              remove a node from the stack;
                              if (node is a goal node) return success;
                              put all children of node onto the stack;
                       }
return failure;

Breadth-first searching:
Put the root node on a queue;
while (queue is not empty)
                        {
                            remove a node from the queue;
                            if (node is a goal node) return success;
                            put all children of node onto the queue;
                        }
return failure;

Note: Queue (FIFO), Stack(LIFO) 
8 Queen problem using DFS Approach link
Reference - Study Material from Site

No comments: