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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值