用邻接表构造图并遍历

/*
输入格式
0 1
0 2
0 3
2 3
1 0
2 0
3 0
3 2
*/
#include <iostream>
using namespace std;

const int maxSize = 10;//图的最大容量为10
struct ArcNode
{
    int adjvex;//邻接域
    ArcNode* next;
};
struct VertexNode
{
    int vertex;//顶点
    ArcNode* firstedge;//指向边表的第一个节点
};
class MyGraph
{
public:
    MyGraph(int a[],int n,int m);
    ~MyGraph(){};
    void DFSTraverse(int v);
    void BFSTraverse(int v);
private:
    VertexNode adjlist[maxSize];
    int* visited;
    int arcNum;
    int verNum;
};
MyGraph::MyGraph(int a[],int n,int m)
{
    arcNum = n;
    verNum = m;
    visited = new int[maxSize];
    for(int i = 0;i < verNum;i++)
    {
        visited[i] = 0;
    }
    for(int i = 0;i < verNum;i++)
    {
        adjlist[i].vertex = a[i];
        adjlist[i].firstedge = NULL;
    }
    for(int k = 0;k < arcNum * 2;k++)
    {
        ArcNode* s = new ArcNode;
        int i,j;
        cin >> i >> j;
        s->adjvex = j;
        s->next = adjlist[i].firstedge;
        adjlist[i].firstedge = s;
    }
}
void MyGraph::DFSTraverse(int v)
{
    ArcNode* p;
    cout << adjlist[v].vertex;
    visited[v] = 1;
    p = adjlist[v].firstedge;
    while(p != NULL)
    {
        v = p->adjvex;
        if(visited[v] == 0)
        {
            DFSTraverse(v);
        }
        p = p->next;
    }
}
void MyGraph::BFSTraverse(int v)
{
    ArcNode* p;
    int myqueue[maxSize];
    int j,head = 0,tail = 0;
    cout << adjlist[v].vertex;
    visited[v] = 1;
    myqueue[tail++] = v;
    while(head != tail)
    {
        v = myqueue[head++];
        p = adjlist[v].firstedge;
        while(p != NULL)
        {
            j = p->adjvex;
            if(visited[j] == 0)
            {
                cout << adjlist[j].vertex;
                visited[j] = 1;
                myqueue[tail++] = j;
            }
            p = p->next;
        }
    }
}
int main()
{
    int a[4] = {0,1,2,3};
    MyGraph myGraph(a,4,4);
    myGraph.BFSTraverse(0);
    return 0;
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/Geek_sun/article/details/80497298
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞