图的建立与遍历

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;

template<class ElemType>
struct Edge
{
    int adj_vertex;
    Edge<ElemType> *next_edge;
};

template<class ElemType>
struct Vertex
{
    ElemType data;
    Edge<ElemType> *first_edge;
};


template<class ElemType>
class ListGraph
{
protected:
    int VexNum;
    int EdgeNum;
    Vertex<ElemType> adjList[500];
public:
    void Create();

    void DFS(int v,bool visited[]) const;
    void DFSTraverse() const;

    void BFS(int v,bool visited[]) const;
    void BFSTraverse() const;
};

template<class ElemType>
void ListGraph<ElemType>::Create()
{
    int i;
    int v1,v2;
    cin>>VexNum>>EdgeNum;
    for(i=0;i<VexNum;i++)
    {
        cin>>adjList[i].data;
        adjList[i].first_edge=NULL;
    }

    for(i=0;i<EdgeNum;i++)
    {
        cin>>v1>>v2;
        Edge<ElemType> *p;
        p=new Edge<ElemType>;
        p->adj_vertex=v2;
        p->next_edge=adjList[v1].first_edge;
        adjList[v1].first_edge=p;

        p=new Edge<ElemType>;
        p->adj_vertex=v1;
        p->next_edge=adjList[v2].first_edge;
        adjList[v2].first_edge=p;
    }
}

template<class ElemType>
void ListGraph<ElemType>::DFS(int v,bool visited[]) const
{
    Edge<ElemType> *p;
    int w;
    visited[v]=true;
    cout<<adjList[v].data<<' ';
    p=adjList[v].first_edge;

    while(p!=NULL)
    {
        w=p->adj_vertex;
        if(!visited[w]) DFS(w,visited);
        p=p->next_edge;
    }
}

template<class ElemType>
void ListGraph<ElemType>::DFSTraverse() const
{
    bool visited[500];
    int v;
    for(v=0;v<VexNum;v++)
    {
        visited[v]=false;
    }

    for(v=0;v<VexNum;v++)
    {
        if(!visited[v]) DFS(v,visited);
    }
    cout<<endl;
}

template<class ElemType>
void ListGraph<ElemType>::BFS(int v,bool visited[]) const
{
    queue<int>q;
    q.push(v);
    cout<<adjList[v].data<<' ';
    visited[v]=true;
    while(!q.empty())
    {
        int w=q.front();
        q.pop();
        Edge<ElemType> *p=adjList[v].first_edge;
        while(p!=NULL)
        {
            int t=p->adj_vertex;
            if(!visited[t])
            {
                q.push(t);
                visited[t]=true;
                cout<<adjList[t].data<<' ';
            }
            p=p->next_edge;
        }
    }
}

template<class ElemType>
void ListGraph<ElemType>::BFSTraverse() const
{
    bool visited[500];
    int v;
    for(v=0;v<VexNum;v++)
    {
        visited[v]=false;
    }

    for(v=0;v<VexNum;v++)
    {
        if(!visited[v]) BFS(v,visited);
    }
}

int main()
{

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值