#include <stdio.h>
#include <malloc.h>
#include <string.h>
using namespace std;
#define MAXVEX 20 //假设的最大顶点数
int visited[100]={0};
typedef char VertexType[3] ;/*数组类型*/
typedef struct vertex /*顶点类型*/
{ int adjvex; /*顶点编号*/
int data; /*顶点的信息*/
} VType;
typedef struct graph
{ int n,e; /*n为实际顶点数,e为实际边数*/
VType vexs[MAXVEX]; /*顶点集合*/
int edges[MAXVEX][MAXVEX]; /*边的集合*/
} AdjMatix; /*图的邻接矩阵类型*/
typedef struct edgenode
{ int adjvex; /*邻接点序号*/
int value; /*边的权值*/
struct edgenode *next; /*下一条边的顶点*/
} ArcNode; /*每个顶点建立的单链表中结点的类型*/
typedef struct vexnode
{ int data; /*结点信息*/
ArcNode *firstarc; /*指向第一条边结点*/
} VHeadNode; /*单链表的头结点类型*/
typedef struct
{ int n,e; /*n为实际顶点数,e为实际边数*/
VHeadNode adjlist[MAXVEX]; /*单链表头结点数组*/
} AdjList;
void MatToList(AdjMatix g,AdjList *&G)
{
int i,j;
ArcNode *p;
G=(AdjList *)malloc(sizeof(AdjList));
for (i=0;i<g.n;i++)
{
G->adjlist[i].firstarc=NULL;
G->adjlist[i].data=g.vexs[i].data;
}
for (i=0;i<g.n;i++)
for (j=0;j<g.n;j++)
if (g.edges[i][j]!=0)
{p=(ArcNode *)malloc(sizeof(ArcNode));
p->value=g.edges[i][j];p->adjvex=j+1;
p->next=G->adjlist[i].firstarc;
G->adjlist[i].firstarc=p;
}
G->n=g.n;G->e=g.e;
}
void DispAdjList(AdjList *G)
{
int i;
ArcNode *p;
for (i=0;i<G->n;i++)
{
printf("%d:",G->adjlist[i].data);
p=G->adjlist[i].firstarc;
while (p!=NULL)
{ printf("%d ",p->adjvex);
p=p->next;
}
printf("\n");
}
}
void DFS1(AdjList *G,int vi)
{
ArcNode *p;
ArcNode *St[MAXVEX];
int top=-1,v;
printf("v%d ",vi+1);
visited[vi+1]=1;
top++;
St[top]=G->adjlist[vi].firstarc;
while (top>-1)
{ p=St[top];top--;
//printf("p1->%d\n",p->adjvex);
while (p!=NULL)
{ v=p->adjvex;
if (visited[v]==0)
{
printf("v%d ",v);
visited[v]=1;
top++;
St[top]=G->adjlist[v-1].firstarc;
break;
}
p=p->next;
St[++top]=p;
//printf("p2->%d\n",p->adjvex);
}
}
}
int main()
{
int i,j,x,y,a[20],b[20],c[20];
AdjMatix g;
AdjList *G;
scanf("%d%d",&g.n,&g.e);
for (i=0;i<g.n;i++)
scanf("%d",&g.vexs[i].data);
for(i=0;i<g.n;i++)
for(j=0;j<g.n;j++)
g.edges[i][j]=0;
for(i=0;i<g.e;i++)
{
scanf("%d%d",&x,&y);
g.edges[x-1][y-1]=1;
g.edges[y-1][x-1]=g.edges[x-1][y-1];
}
MatToList(g,G);
//DispAdjList(G);
DFS1(G,0);
return 0;
}
瑞格7042--采用邻接表存储实现无向图的深度优先非递归遍历。
最新推荐文章于 2022-12-15 17:58:52 发布