图的遍历(邻接矩阵的非递归实现)

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;


typedef char TypeData;
#define MAXVEX 100
#define INFINITY 65535
int visited[MAXVEX]={0};
int stack[MAXVEX];
queue<int> q;

typedef struct stGraph
{
    TypeData vexs[MAXVEX];//存放图中顶点的数组
    int arc[MAXVEX][MAXVEX];//邻接矩阵
    int VNum,ENum;//顶点数、边数
}MGraph;

void CreatMGraph(MGraph *G);
void DFSTraverse(MGraph *G);
void BFSTraverse(MGraph *G);

void CreatMGraph(MGraph *G)
{
    int i=0,j=0,k=0,w=0;
    cout<<"请输入顶点数和边数:"<<endl;
    cin>>G->VNum>>G->ENum;

    cout<<"请输入图的顶点:";
    for(i=0;i<G->VNum;i++)
    {
        cin>>G->vexs[i];
    }

    for(i=0;i<G->VNum;i++)
        for(j=0;j<G->VNum;j++)
    {
        G->arc[i][j]=INFINITY;
    }

    for(k=0;k<G->ENum;k++)
    {
        cout<<"请输入(vi,vj)上的下标,i,j,和权值w:"<<endl;
        cin>>i>>j>>w;
        G->arc[i][j]=w;
        G->arc[j][i]=w;
    }
}

void DFSTraverse(MGraph *G,int v)
{
   int top=-1;
   int j;
   cout<<G->vexs[v]<<" "; visited[v]=1;
   stack[++top]=v;
   while(top!=-1)
   {
       v=stack[top];
       for(j=0;j<G->VNum;j++)
       if(G->arc[v][j]!=INFINITY&&visited[j]==0){
        cout<<G->vexs[j]<<" ";
        visited[j]=1;
        stack[++top]=j;
        break;
       }
       if(j==G->VNum) top--;
   }
}

void BFSTraverse(MGraph *G)
{
    int i,j;
    for(i=0;i<G->VNum;i++) visited[i]=0;

    queue<int> q;
    for(i=0;i<G->VNum;i++)
    {
        if(visited[i]==0)
        {
            cout<<G->vexs[i]<<" ";
            visited[i]=1;
            q.push(i);
            while(!q.empty())
            {
                i=q.front();
                q.pop();
                for(j=0;j<G->VNum;j++)
                if(G->arc[i][j]!=INFINITY&&visited[j]==0){
                    cout<<G->vexs[j]<<" ";
                    visited[j]=1;
                    j=q.front();
                }
            }
        }
    }


}
int main()
{
    MGraph *G=new MGraph;
    int v;
    CreatMGraph(G);
    cout<<"请输入要作为源点的顶点的下标值:"<<endl;
    cin>>v;
    cout<<"该图的深度优先遍历顺序为:"<<endl;
    DFSTraverse(G,v);
    cout<<endl;
    cout<<"该图的广度优先遍历顺序为:"<<endl;
    BFSTraverse(G);

    return 0;
}





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