DFS is the basic tree search technique in which goal,data is searched by moving downward until a leaf,end node, is reached.Then it backtrack and repeat the moving down to leaf process.This process is repeated until the searching data is found.
Algorithm
An algorithm for the depth – first search is the same as that for breadth first search except in the ordering of the nodes.
- Place the starting node s on the top of the stack.
- If the stack is empty, return failure and stop.
- If the element on the stack is goal node g, return success and stop. Otherwise,
- Remove and expand the first element , and place the children at the top of the stack.
- Return to step 2.
#include <iostream>#include <ctime>#include <malloc.h>usingnamespacestd;structnode{intinfo;structnode *next;};classstack{structnode *top;public:stack();voidpush(int);intpop();boolisEmpty();voiddisplay();};stack::stack(){top = NULL;}voidstack::push(intdata){node *p;if((p=(node*)malloc(sizeof(node)))==NULL){cout<<"Memory Exhausted";exit(0);}p =newnode;p->info = data;p->next = NULL;if(top!=NULL){p->next = top;}top = p;}intstack::pop(){structnode *temp;intvalue;if(top==NULL){cout<<"\nThe stack is Empty"<<endl;}else{temp = top;top = top->next;value = temp->info;deletetemp;}returnvalue;}boolstack::isEmpty(){return(top == NULL);}voidstack::display(){structnode *p = top;if(top==NULL){cout<<"\nNothing to Display\n";}else{cout<<"\nThe contents of Stack\n";while(p!=NULL){cout<<p->info<<endl;p = p->next;}}}classGraph {private:intn;int**A;public:Graph(intsize = 2);~Graph();boolisConnected(int,int);voidaddEdge(intx,inty);voidDFS(int,int);};Graph::Graph(intsize) {inti, j;if(size < 2) n = 2;elsen = size;A =newint*[n];for(i = 0; i < n; ++i)A[i] =newint[n];for(i = 0; i < n; ++i)for(j = 0; j < n; ++j)A[i][j] = 0;}Graph::~Graph() {for(inti = 0; i < n; ++i)delete[] A[i];delete[] A;}boolGraph::isConnected(intx,inty) {return(A[x-1][y-1] == 1);}voidGraph::addEdge(intx,inty) {A[x-1][y-1] = A[y-1][x-1] = 1;}voidGraph::DFS(intx,intrequired){stack s;bool*visited =newbool[n+1];inti;for(i = 0; i <= n; i++)visited[i] =false;s.push(x);visited[x] =true;if(x == required)return;cout <<"Depth first Search starting from vertex ";cout << x <<" : "<< endl;while(!s.isEmpty()){intk = s.pop();if(x == required)break;cout<<k<<" ";for(i = n; i >= 0 ; --i)if(isConnected(k, i) && !visited[i]) {s.push(i);visited[i] =true;}}cout<<endl;delete[] visited;}intmain(){Graph g(8);g.addEdge(1, 2); g.addEdge(1, 3); g.addEdge(1, 4);g.addEdge(2, 5); g.addEdge(2, 6); g.addEdge(4, 7);g.addEdge(4, 8);g.DFS(1, 4);return0;}
very informative post indeed .being enrolled in http://www.wiziq.com/course/5776-object-oriented-programming-with-c
ReplyDeletei was looking for such articles online to assist me and your article helped me a lot. i really like that you are providing such information.