抱歉,代码有点小瑕疵,已紧急修复,修复时间:2020-12-21 下午10:30
具体行已在代码中注释标出
算法思想:
1、创建:8会。
2、深度优先搜索生成树:8会。
流程图:
实验六可能会停更了。
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1 /*状态码预定义*/
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAX_VERTAX_NUM 20 //最大顶点个数
typedef char Vertextype;
typedef struct ArcNode{
int adjvex;
struct ArcNode *nextarc;
}ArcNode;
typedef struct VNode
{
Vertextype data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTAX_NUM];
typedef struct
{
AdjList vertices;
int vexnum,arcnum;
int kind;
}ALGraph;
typedef struct CSNode
{
Vertextype e;
CSNode *lchild,*nextsibling;
}CSNode,*CSTree;
int visited[MAX_VERTAX_NUM];
int LocateVex(ALGraph G,char e)
{
int i;
for(i=0;i<G.vexnum;i++)
{
if(G.vertices[i].data==e)
return i;
}
return -1;
}
void CreateUDG(ALGraph &G)
{
int i,k,j;
ArcNode *p,*s;
char v1,v2;
printf("图的种类已默认为无向图\n");
G.kind=1;
printf("请输入顶点数和边数:(空格区分)");
scanf("%d%d",&G.vexnum,&G.arcnum);
getchar();
printf("开始建立顶点表\n");
for(i=0;i<G.vexnum;i++)
{
printf("请输入第%d个顶点的信息:",i+1);
G.vertices[i].data=getchar();
getchar();
G.vertices[i].firstarc=NULL;
}
printf("建立边表\n");
for(k=0;k<G.arcnum;k++)
{
printf("请输入两个顶点(例:ab代表a~b):");
scanf("%c%c",&v1,&v2);
getchar();
i=LocateVex(G,v1);
j=LocateVex(G,v2);
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex=j;
p->nextarc=G.vertices[i].firstarc;
G.vertices[i].firstarc=p;
s=(ArcNode*)malloc(sizeof(ArcNode));
s->adjvex=i;
s->nextarc=G.vertices[j].firstarc;
G.vertices[j].firstarc=s;
}
printf("边表建立完成\n");
}
void DispGraph(ALGraph G)
{
int i;
printf("打印邻接表:\n");
for (i=0;i<G.vexnum;i++)
{
printf("%d->",i);
while(1)
{
if(G.vertices[i].firstarc==NULL)
{
printf("^");
break;
}
printf("%d->",G.vertices[i].firstarc->adjvex);
G.vertices[i].firstarc=G.vertices[i].firstarc->nextarc;
}
printf("\n");
}
}
Vertextype GetVex(ALGraph G,int v)
{
return G.vertices[v].data;
}
void DFSTree(ALGraph G,int v,CSTree &T)
{
int w,first;
CSTree p,q;
ArcNode *temp;
visited[v]=TRUE;
first = 1;
temp=G.vertices[v].firstarc;
while(temp!=NULL)
{
w=temp->adjvex;
if(visited[w]==0)
{
p=(CSTree)malloc(sizeof(CSNode));
p->e=GetVex(G,w); //原"GetVex(G,v)";将v改为w即可
p->lchild=NULL;
p->nextsibling=NULL;
if(first)
{T->lchild=p;first=0;}
else
q->nextsibling=p;
q=p;
DFSTree(G,w,q);
}
temp=temp->nextarc;
}
}
void DFSForest(ALGraph G,CSTree &T)
{
int v;
CSTree p,q;
T=NULL;
for(v=0;v<G.vexnum;v++)
visited[v]=FALSE;
for(v=0;v<G.vexnum;v++)
{
if(!visited[v])
{
p=(CSTree)malloc(sizeof(CSNode));
p->e=GetVex(G,v);
p->lchild=NULL;
p->nextsibling=NULL;
if(!T) T=p;
else q->nextsibling=p;
q=p;
DFSTree(G,v,p);
}
}
}
void PreOrderTraverse(CSTree T)
{
if(T==NULL) return;
printf("%c",T->e);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->nextsibling);
}
int main()
{
ALGraph G; //图
CSTree T; //树
CreateUDG(G); //建图
DispGraph(G); //画表
DFSForest(G,T); //种树
printf("先序遍历开始\n");
PreOrderTraverse(T); //先序遍历
system("pause");
return 0;
}