DFS and BFS

#include<iostream>
#include<fstream>
#include<queue>
using namespace std;
class Graph
{ 
  
  private:
      int **eage;
      int n;
      int e;
	  int *visted;
	  queue<int> intq;
  public:
	  Graph(int n,int e);
	  ~Graph();
	  void readGraphFile();
	  void displayDraph();
	  void dfsSearch(int v);
	  void dfs();
	  void bfsSearch(int v);
	  void bfs();
};
Graph::Graph(int ni,int ei)
{
	  n=ni;
	  e=ei;
	  eage=new int *[n];
	  for(int i=0;i<n;i++)
		  eage[i]=new int[n];
	  visted=new int[n];
}
Graph::~Graph()
{
    for(int i=0;i<n;i++)
		delete eage[i];
	delete[] eage;
	delete visted;
}
void Graph::readGraphFile()
{ 
     ifstream ifs;
	 char buf;
	 int p=0;
	 int q=0;
     ifs.open("graph.txt");
	 while(!ifs.eof())
	 {
	       ifs.get(buf);
	       if(buf=='1'||buf=='0')
		   { 
		      eage[p][q%n]=buf-'0';
		      q++;
		      if(q%n==0)
    		     p++;
		   }
	 }
}
void Graph::displayDraph()
{
    for(int i=0;i<n;i++)
	{
		for(int j=0;j<n;j++)
		  cout<<eage[i][j]<<" ";
		cout<<endl;
	}
}
void Graph::dfsSearch(int v)
{
	 visted[v]=1;
     for(int i=0;i<n;i++)
		 if(eage[v][i]==1)
		 {   
               cout<<v<<"--->"<<i<<endl;
			   if(visted[i]!=1)		
				dfsSearch(i);	    
		 }
}
void Graph::dfs()
{    
       for(int i=0;i<n;i++)
		   if(visted[i]!=1)
			   dfsSearch(i);         
}
void Graph::bfsSearch(int v)
{      
	   intq.push(v);
	   visted[v]=1;
	   while(!intq.empty())
       {   
		    int  w=intq.front();
			intq.pop();
             for(int i=0;i<n;i++)	
				 if(eage[w][i]==1)
				 {        
					        cout<<w<<"--->"<<i<<endl;
					        if(visted[i]!=1)
							{
                              visted[i]=1;
                               intq.push(i);
							}
				 }
  	   }
}
void Graph::bfs()
{
     for(int i=0;i<n;i++)
		 if(visted[i]!=1)
			 bfsSearch(i);
}
int main()
{
    Graph *g=new Graph(4,16);
    g->readGraphFile();
	g->displayDraph();
    char choose;
	while(cin>>choose)
	{
		switch(choose)
		{
		  case  'd': g->dfs(); break;
		  case  'b':  g->bfs();break;
		  default:;
		}
	}
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值