/*/*
DFS深度优先遍历邻接表
*/
#include <iostream>
#include <malloc.h>
using namespace std;
#define MAX 20
typedef struct e_node//表节点
{
int vex;//索引值
struct e_node *next;
}*enode;
typedef struct v_node//头节点
{
int data;
struct e_node *next;
}head,*vnode;
typedef struct G_list//图的邻接表
{
head lead[MAX];//存放头节点
int vexnum,arcnum;//节点数,弧数
}*graph;
int get_pos(graph map,char in)//失败返回-1
{
for(int i=0;i<map->vexnum;i++)
{
if(in==map->lead[i].data)return i;
}
return -1;
}
void link_last(enode list,enode node)
{
while(list->next)
{
list=list->next;
}
list->next=node;
}
/*用户输入创建图*/
graph creat_graph()
{
int vex,arc;
char temp;
char in1,in2;
int p1,p2;
graph map;
cout<<"请输入顶点数:"<<endl;
cin>>vex;
cout<<"请输入弧数:"<<endl;
cin>>arc;
map=(graph)malloc(sizeof(G_list));
memset(map,0,sizeof(sizeof(G_list)));
//初始化
map->arcnum=arc;
map->vexnum=vex;
//////////////////
//初始化邻接表的顶点
for(int i=0;i<vex;i++)
{
printf("请输入lead[%d]\n",i);
cin>>temp;
map->lead[i].data=temp;
map->lead[i].next=NULL;
}
//初始化弧
for(int j=0;j<arc;j++)
{
cout<<"输入边弧:"<<endl;
cin>>in1>>in2;
p1=get_pos(map,in1);
p2=get_pos(map,in2);
enode arc_side1=(enode)malloc(sizeof(e_node));
arc_side1->vex=p1;
arc_side1->next=NULL;
if(map->lead[p2].next==NULL)//空的话
map->lead[p2].next=arc_side1;
else
link_last(map->lead[p2].next,arc_side1);
enode arc_side2=(enode)malloc(sizeof(e_node));
arc_side2->vex=p2;
arc_side2->next=NULL;
if(map->lead[p1].next==NULL)//空的话
map->lead[p1].next=arc_side2;
else
link_last(map->lead[p1].next,arc_side2);
}
return map;
}
void DFS(graph map,int i,int *visit)
{
enode node;
visit[i]=1;//标志
cout<<(char)map->lead[i].data<<" ";
node=map->lead[i].next;
while(node!=NULL)//邻接表有元素
{
if(visit[node->vex]==0)//尚未遍历
{
DFS(map,node->vex,visit);
}//如果遍历
node=node->next;
}
}
void BFS(graph map,int *visit)
{
int head,rear;
int quene[MAX];
int k,temp,var;
head=rear=0;
enode node;
for(int j=0;j<map->vexnum;j++)
{
if(visit[j]==0)
{
visit[j]=1;
cout<<(char)map->lead[j].data<<" ";
quene[rear++]=j;
}
while(head!=rear)
{
k=quene[head++];//出队
node=map->lead[k].next;
while(node!=NULL)
{
var=node->vex;
if(visit[var]==0)
{
visit[var]=1;
cout<<(char)map->lead[var].data<<" ";
quene[rear++]=var;
}
node=node->next;
}
}
}
}
void main()
{
int visit[MAX];
memset(visit,0,sizeof(visit));
graph map=creat_graph();//创建图
//DFS(map,0,visit);
cout<<"BFS:"<<endl;
BFS(map,visit);
}