DFS BFS遍历图 邻接表实现

#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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值