实验六:图的邻接矩阵存储方式(无向图)

源程序:

# include

using namespace std;

const int MAXSIZE=10;

int visited[MAXSIZE]={0};

class MGraph

{

public:

MGraph(char a[],int n,int e);

    ~MGraph(){}

    void DFSTraverse(int v);

    void BFSTraverse(int v);

    void Print(int v);

    void PrintV();

private:

    char vertex[MAXSIZE];

    int arc[MAXSIZE][MAXSIZE];

     int vertexNum,arcNum;

};

MGraph::MGraph(char a[],int n,int e)

{

int i,j,k;

vertexNum=n;

arcNum=e;

for(i=0;i

    vertex[i]=a[i];

for(i=0;i

for(j=0;j

arc[i][j]=0;

for(k=0;k

{

cout<<"请输入边的两个顶点的序号:";

cin>>i>>j;

arc[i][j]=1;

arc[j][i]=1;

}

}

void MGraph::DFSTraverse(int v)

{

    cout<

     visited[v]=1;

  for(int j=0;j

  if(arc[v][j]==1&&visited[j]==0)

          DFSTraverse(j);

}

void MGraph::BFSTraverse(int v)

{

  int Q[MAXSIZE];

  int front=-1,rear=-1;

 cout<

 visited[v]=1;

 Q[++rear]=v;

   while(front!=rear)

  {

    v=Q[++front];

   for(int j=0;j

      if(arc[v][j]==1&&visited[j]==0)

      {

        cout<

          visited[j]=1;

         Q[++rear]=j;

      }

   }

}

void MGraph::Print(int v)

{

  int i,j;

  for(i=0;i

  {

  for(j=0;j

  {

  if(arc[v][i]==1&&arc[v][j]==1)

  cout<<"1:"<

  }

  }

 cout<

}

void MGraph::PrintV()

{

int i;

for(i=0;i

cout<

}

int main()

{

   

char ch[]={'A','B','C','D','E'};

MGraph MG(ch,5,6);

for(int i=0;i

visited[i]=0;

cout<<"深度优先遍历序列:";

MG.DFSTraverse(0);

cout<

for( i=0;i

visited[i]=0;

cout<<"广度优先遍历序列是:";

MG.BFSTraverse(0);

cout<

int number=5;

    for(i=0;i

MG.Print(i);

MG.PrintV();

cout<

return 0;

}

程序结果:

实验六:图的邻接矩阵存储方式(无向图)_第1张图片

你可能感兴趣的:(实验六:图的邻接矩阵存储方式(无向图))