无向图的创建和两种遍历



// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//

#include “stdafx.h”
#include<iostream>
using namespace std;
#define maxSize (100)
typedef struct ArcNode{//弧结点
 int info;//弧信息
 struct ArcNode* nextarc;//指向下一个弧结点的指针
 int adjvex;//弧指向结点在顺序表中的序号
}ArcNode;

typedef struct VNode{//定点结点
 char data;//定点结点值
 ArcNode*firstarc;//指向的第一条弧结点
}VNode;

typedef struct AGraph{
 VNode adjlist[maxSize];//顶点列表
 int e, n;//弧和顶点数目
}AGraph;

int adjloction(AGraph*G, char v)//查询顶点值为v的顶点在顺序链表中的位置
{
 for (int i = 0; i < G->n; ++i)
  if (G->adjlist[i].data == v)
   return i;
 return -1;
}
void CreateAGraph(AGraph *&G)//创建图
{
 G = (AGraph*)malloc(sizeof(AGraph));
 cout << “输入顶点数和弧数:” << endl;
 cin >> G->n >> G->e;

 cout << “输入顶点:” << endl;
 for (int i = 0; i < G->n; ++i)
 {
  cin >> G->adjlist[i].data;
  G->adjlist[i].firstarc = NULL;
 }

 cout << “输入弧:” << endl;
 for (int i = 0; i < G->e; ++i)
 {
  ArcNode *arc = (ArcNode*)malloc(sizeof(ArcNode));
  char v1, v2;
  int a1, a2;
  cin >> v1 >> v2;
  a1 = adjloction(G, v1);
  a2 = adjloction(G, v2);
  arc->adjvex = a2;
  //cin >> arc->info;
  arc->nextarc = G->adjlist[a1].firstarc;
  G->adjlist[a1].firstarc = arc;

  arc = (ArcNode*)malloc(sizeof(ArcNode));
  arc->adjvex = a1;
  //cin>>arc->info;
  arc->nextarc = G->adjlist[a2].firstarc;
  G->adjlist[a2].firstarc = arc;
 }
}

void Print(AGraph *G)//打印邻接表
{
 ArcNode *p;
 for (int i = 0; i < G->n; ++i)
 {
  cout << G->adjlist[i].data<<endl;
  p = G->adjlist[i].firstarc;//p为第一条弧
  while (p)
  {
   cout << ” ->” << G->adjlist[p->adjvex].data<<endl;
   p = p->nextarc;
  }
 }
}

int visit[maxSize];
void DFS(AGraph*G, char v)//深搜
{
 cout << G->adjlist[adjloction(G, v)].data << endl;
 visit[adjloction(G, v)] = 1;//标记已搜索
 ArcNode*p = G->adjlist[adjloction(G, v)].firstarc;
 while (p)
 {
  if (visit[p->adjvex] != 1)
   DFS(G, G->adjlist[p->adjvex].data);
  p = p->nextarc;
 }
}

void BFS(AGraph*G, char v)//广搜
{
 int queue[maxSize];
 int mvisit[maxSize];
 int rear=0,  front = 0;
 int j;

 cout << v << endl;
 mvisit[adjloction(G, v)] = 1;

 rear = (rear + 1) % maxSize;
 queue[rear] = adjloction(G, v);

 while (rear!=front)//队列是否为空
 {
  front = (front + 1) % maxSize;
  j = queue[front];
  //cout << G->adjlist[j].data << endl;
  //mvisit[j] = 1;//标记为已访问
  ArcNode*p = G->adjlist[j].firstarc;
  while (p)
  {
   if (mvisit[p->adjvex] != 1)
   {
    cout << G->adjlist[p->adjvex].data << endl;
    mvisit[p->adjvex] = 1;
    rear = (rear + 1) % maxSize;
    queue[rear] = p->adjvex;
   }
   p = p->nextarc;
  }
 }
}
int _tmain(int argc, _TCHAR* argv[])
{
 AGraph*G;
 CreateAGraph(G);
 cout << “打印邻接表:” << endl;
 Print(G);
 cout << “打印深度优先搜索结果:” << endl;
 DFS(G, G->adjlist[0].data);
 cout << “打印广度优先搜索结果:” << endl;
 BFS(G, G->adjlist[0].data);
 return 0;
}

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