Depth First Search in C++ – Algorithm and Source Code

Basic Theory
Depth – first searches are performed by diving downward into a tree as quickly as possible. It does this by always generating a child node from the most recently expanded node, then generating that child’s children, and so on until a goal is found or some cutoff depth point d is reached. If a goal is not found when a leaf node is reached or at the cutoff point, the program backtracks to the most recently expanded node and generates another of its children. This process continues until a goal is found or failure occurs.
Algorithm
An algorithm for the depth – first search is the same as that for breadth first search except in the ordering of the nodes.

  1. Place the starting node s on the top of the stack.
  2. If the stack is empty, return failure and stop.
  3. If the element on the stack is goal node g, return success and stop. Otherwise,
  4. Remove and expand the first element , and place the children at the top of the stack.
  5. Return to step 2.
Example
Source Code
#include 
#include 
#include  
using namespace std;
struct node{
    int info;
    struct node *next;
}; 

class stack{
    struct node *top;
    public:
        stack();
        void push(int);
        int pop();
        bool isEmpty();
        void display();
}; 

stack::stack(){
    top = NULL;
} 

void stack::push(int data){
    node *p;
    if((p=(node*)malloc(sizeof(node)))==NULL){
        coutinfo = data;
    p->next = NULL;
    if(top!=NULL){
        p->next = top;
    }
    top = p;
} 

int stack::pop(){
    struct node *temp;
    int value;
    if(top==NULL){
        coutnext;
        value = temp->info;
        delete temp;
    }
    return value;
} 

bool stack::isEmpty(){
    return (top == NULL);
} 

void stack::display(){
    struct node *p = top;
    if(top==NULL){
        coutinfonext;
        }
    }
} 

class Graph {
    private:
        int n;
        int **A;
    public:
        Graph(int size = 2);
        ~Graph();
        bool isConnected(int, int);
        void addEdge(int x, int y);
        void DFS(int , int);
}; 

Graph::Graph(int size) {
    int i, j;
    if (size = 0 ; --i)
            if (isConnected(k, i) && !visited[i]) {
                s.push(i);
                visited[i] = true;
            }
    }
    cout

Complexity

The depth – first search is preferred over the breadth – first when the search tree is known to have a plentiful number of goals. The time complexity of the depth-first tree search is the same as that for breadth-first, O(bd). It is less demanding in space requirements, however, since only the path form the starting node to the current node needs to be stored. Therefore, if the depth cutoff is d, the space complexity is just O(d).