您的位置:首页 > 其它

DFS BFS遍历图 邻接表实现

2012-12-14 12:25 483 查看
#include<iostream>
#include<queue>
#include<stack>
#include<map>
#include<cstring>
using namespace std;
#define MAX 1000
map<char,bool> maps;
map<char,bool>::iterator it;
struct edge
{
char c;
edge *next;
edge():next(NULL){}
};
struct vertex
{
char c;
edge *next;
vertex():next(NULL){}
};
vertex ver[MAX];
void DFS(int num)
{
stack<vertex> sta;
vertex temp;
edge *te;
sta.push(ver[0]);
while(!sta.empty())
{
temp=sta.top();
if(!maps[temp.c])
{
cout<<temp.c<< ' ';
maps[temp.c]=true;
}
sta.pop();
te=temp.next;
while(te)
{
if(!maps[te->c])
sta.push(ver[te->c-'A']);
te=te->next;
}
}
cout<<endl;
}
void BFS(int num)
{
queue<vertex> que;
vertex temp;
edge *te;
que.push(ver[0]);
while(!que.empty())
{
temp=que.front();
if(!maps[temp.c])
{
cout<<temp.c<< ' ';
maps[temp.c]=true;
}
que.pop();
te=temp.next;
while(te)
{
if(!maps[te->c])
que.push(ver[te->c-'A']);
te=te->next;
}
}
cout<<endl;
}
int main()
{
int  num,ednum,state;
char c,d;
edge *p,*t;
cout<<"输入顶点数,边数"<<endl;
cin>>num>>ednum;
cout<<"输入何种图 1:有向图 0:无向图"<<endl;
cin>>state;
cout<<"输入"<<num<<"个顶点,必须是正序大写字母如:A B C D E F G H"<<endl;
for(int i=0;i<num;i++)
{
cin>>ver[i].c;
maps[ver[i].c]=false;
}
cout<<"输入"<<ednum<<"条边,如:A B"<<endl;
for(int i=0;i<ednum;i++)
{
cin>>c>>d;
p=new edge;
p->c=d;
if(ver[c-'A'].next==NULL)
ver[c-'A'].next=p;
else
{
t=ver[c-'A'].next;
while(t->next)
t=t->next;
t->next=p;
}
if(!state)
{
p=new edge;
p->c=c;
if(ver[d-'A'].next==NULL)
ver[d-'A'].next=p;
else
{
t=ver[d-'A'].next;
while(t->next)
t=t->next;
t->next=p;
}
}
}
cout<<"输入需要操作的序号!"<<endl
<<"1.广度搜索	2.深度搜索"<<endl;
while(cin>>c)
{
switch(c)
{
case '1':
BFS(num);
for(it=maps.begin();it!=maps.end();++it)
(*it).second=false;
break;
case '2':
DFS(num);
for(it=maps.begin();it!=maps.end();++it)
(*it).second=false;
break;
default:
break;
}
cout<<"输入需要操作的序号!(EOF结束(Ctrl+Z))"<<endl
<<"1.广度搜索	2.深度搜索"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: