Friday, March 7, 2014

Graph BFS + DFS traverse

BFS: Using queue
DFS: Using recursion, also can use stack.

Answer:
C++ code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

class UndirectedGraphNode {
 public:
int label;
    bool visited;
vector<UndirectedGraphNode *> neighbors;

    UndirectedGraphNode(int x){
label=x;
visited = false;
}
    ~UndirectedGraphNode(){
}  
};

void concat(UndirectedGraphNode *p, UndirectedGraphNode *q){
p->neighbors.push_back(q);
q->neighbors.push_back(p);
}

vector<int> BFS (UndirectedGraphNode* node){
        queue<UndirectedGraphNode*> que;
        vector<int>  res;
        que.push(node);
node->visited=true;
int currnum=1;
int nextnum=0;

        while(!que.empty()){
             UndirectedGraphNode* cur = que.front();
             que.pop();
             res.push_back(cur->label);     //Only when poping an Node from the queue, add its label to the res.
         currnum--;

             for(int i=0; i < cur->neighbors.size();++i){
                   UndirectedGraphNode* nb= cur->neighbors[i];
                   if(!nb->visited){
                         que.push(nb);
                         nb->visited=true;
                   nextnum++;
                   }
              }

 if(currnum==0){
res.push_back(0);             //'0' is a symbol, means '\n', this level ends.
               std::swap(currnum,nextnum);
          }
         }
         return res;
}

vector<int> DFS(UndirectedGraphNode *node){
node->visited=true;
vector<int> res;
res.insert(res.begin(),node->label);              //recursion base case, no "unvisited" neighbor, only itself.

for(int i=0; i< node->neighbors.size();++i){
UndirectedGraphNode *nb=node->neighbors[i];
if(!nb->visited){
                 vector<int> subres=DFS(nb);                //recursion case, adding subres in preorder order.
                 nb->visited=true;
                 res.insert(res.end(),subres.begin(),subres.end());
}
}
return res;
}

int main(){

UndirectedGraphNode *a= new UndirectedGraphNode(1);
UndirectedGraphNode *b= new UndirectedGraphNode(2);
UndirectedGraphNode *c= new UndirectedGraphNode(3);
UndirectedGraphNode *d= new UndirectedGraphNode(4);
UndirectedGraphNode *e= new UndirectedGraphNode(5);
UndirectedGraphNode *f= new UndirectedGraphNode(6);
//Create graph.
concat(a,b);
concat(b,c);
concat(a,c);
concat(b,d);
concat(d,e);
concat(c,f);

vector<int> result;
//BFS
result= BFS(a);
cout<<"BFS:";
for(int i=0;i<result.size();i++){
cout<<result[i]<<" ";
}
/* 
//DFS
result= DFS(a);
cout<<"DFS:";
for(int i=0;i<result.size();i++){
cout<<result[i]<<" ";
}
*/
getchar();
return 0;
}

No comments:

Post a Comment