您的位置:首页 > 其它

有向图的邻接表建立及其深搜宽搜

2013-11-10 20:42 344 查看
#include<iostream>
#include<cstdlib>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
typedef struct edge
{
int no;
struct edge *next;
}edgetype;//链表节点
typedef struct
{
int mark;
char vertex[10];
edgetype *firstArc;
} vertexnode;//表头节点
typedef struct
{
vertexnode vex[100];
int n,e;
} ALGraph;
ALGraph G;
int Find(char a[])
{
int i;
for(i=0;i<G.n;i++)
if(strcmp(G.vex[i].vertex,a)==0)break;
return i;
}
void DFS(int i)//深搜
{
edgetype *p;
G.vex[i].mark=1;
cout<<G.vex[i].vertex<<" ";
p=G.vex[i].firstArc;
while(p!=NULL)
{
if(G.vex[p->no].mark==0)DFS(p->no);
p=p->next;
}
}
/*void BFS()//宽搜
{
int s,t;
char a[10];
edgetype *p;
queue<int>Q;
while(!Q.empty())Q.pop();
cout<<"请输入宽搜的起点:"<<endl;
cin>>a;
s=Find(a);
G.vex[s].mark=1;
Q.push(s);
cout<<G.vex[s].vertex<<" ";
while(!Q.empty())
{
t=Q.front();
Q.pop();
p=G.vex[t].firstArc;
while(p!=NULL)
{
if(G.vex[p->no].mark==0)
{
cout<<G.vex[p->no].vertex<<" ";
G.vex[p->no].mark=1;
Q.push(p->no);
}
p=p->next;
}
}
}*/
int main()
{
int i,j;
cin>>G.n>>G.e;
for(i=0; i<G.n; i++)
{
cin>>G.vex[i].vertex;
G.vex[i].mark=0;
G.vex[i].firstArc=NULL;
}
for(i=0; i<G.e; i++)
{
int x,y;
char a[5],b[5];
cin>>a>>b;
x=Find(a);
y=Find(b);
edgetype *p,*q;
q=(edgetype*)malloc(sizeof(edgetype));//关键
q->no=y;
q->next=NULL;
if(G.vex[x].firstArc==NULL)G.vex[x].firstArc=q;
else
{
p=G.vex[x].firstArc;
while(p->next!=NULL)p=p->next;
p->next=q;
}
}
/*for(i=0;i<G.n;i++)
{
cout<<G.vex[i].vertex<<" ";
edgetype *p;
p=G.vex[i].firstArc;
while(p!=NULL)
{
cout<<G.vex[p->no].vertex<<" ";
p=p->next;
}
cout<<endl;
}*/
for(i=0; i<G.n; i++)
if(G.vex[i].mark==0)DFS(i);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表 图论 搜索