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

来源:互联网 发布:广州 荔湾区 骏域网络 编辑:程序博客网 时间:2024/04/29 09:14
#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;}