#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;
}
DFS and BFS
最新推荐文章于 2024-07-22 09:38:37 发布