实验要求
- 实现图的抽象数据类型
- 在邻接矩阵结构上实现图的建立运算
- 在邻接表结构上实现图的建立运算
- 实现网的遍历运算(广度优先)
- 实现最短路径算法(floyd)
实验代码
- 实现图的抽象数据类型
//邻接矩阵结构
typedef struct ArcCell
{
EType adj;
InfoType info;
}ArcCell,AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];
typedef struct
{
VertexType vexs[MAX_VERTEX_NUM];
AdjMatrix arcs;
int vexnum,arcnum;
GraphKind kind;
}MGraph;
//邻接表结构
typedef struct ArcNode
{ int adjvex;
struct ArcNode *nextarc;
InfoType *info;
}ArcNode;
typedef struct VNode //define structure ALGraph
{ VertexType data;
ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];
typedef struct
{ AdjList vertices;
int vexnum,arcnum;
int kind;
}ALGraph;
- 在邻接矩阵结构上实现图的建立运算
int CreatUDN(MGraph &G)
{
int i=0,j=0,k,vi,vj,w;
//-----Demo G.vexnum and G.arcnum------
G.vexnum=3;
G.arcnum=5;
//-----------------------------------------
printf("Please input the number of G.vexnum(eg,G.vexnum=3) : ");
scanf("%d",&G.vexnum);
printf("Please input the number of G.arcnum(eg,G.arcxnum=5) : ");
scanf("%d",&G.arcnum);
for(i=0;iVj):"<>vi;
cout<<"Please input the "<>vj;
cout<<"Please input the "<>w;
i=vi;
j=vj;
while(i<1||i>G.vexnum||j<1||j>G.vexnum||w<0)
{
cout<<"Input ERROR!"<>vi;
cout<<"Please input the "<>vj;
cout<<"Please input the "<>w;
i=vi;
j=vj;
}//end of while
i--;
j--;
G.arcs[i][j].info=w;
}//end of for
return (OK);
}//end of CreateUDN() function
- 在邻接表结构上实现图的建立运算
int CreateDG(ALGraph &G) //CreateDG() sub-function
{
int IncInfo,i,j,k,v1,v2,w;
cout<>G.vexnum;
cout<<"请输入图的弧的条数(eg. G.arcnum=4):";
cin>>G.arcnum;
cout<<"请输入图的弧上的信息(0 for none) :";
cin>>IncInfo;
for(i=0;iv2),fo example:(v1=1,v2=3),(v1=2,v2=4)...";
for(k=0;k>v1;
cout<<"请输入第"<>v2;
i=v1;
j=v2;
while(i<1||i>G.vexnum||j<1||j>G.vexnum)//if(v1,v2) illedal again
{
cout<>v1;
cout<<"请输入第"<>v2;
}//while end
i--;
j--;
ArcNode *p;
p=(ArcNode *)malloc(sizeof(ArcNode));//allocate memory
if(!p)
{cout<<"Overflow!"; return(0);}
p->adjvex=j; //assign p
p->nextarc=G.vertices[i].firstarc;
p->info=NULL;
G.vertices[i].firstarc=p;
if(IncInfo)
{cout<<"请输入info:";
cin>>*(p->info);}
}//end of if
return (OK);
}//end of CreateDG()
- 实现网的遍历运算(广度优先)
void BFSTraverse(ALGraph G)//BFSTraverse() sub-function
{
int v,w,u;
int visited[MAX_VERTEX_NUM];
SqQueue Q;
for(v=0;v";
EnQueue(Q,v);
while(!QueueEmpty(Q))
{
DeQueue(Q,u);
for(w=G.vertices[u].data;
G.vertices[u].firstarc!=NULL;
w=G.vertices[u].firstarc->adjvex,
G.vertices[u].firstarc=G.vertices[u].firstarc->nextarc)//"右)"
if(visited[w]==0)
{
visited[w]=1;
cout<";
EnQueue(Q,w);
}//if end
if(visited[w]==0)
{
visited[w]=1;
cout<";
EnQueue(Q,w);
}//if end
}//while end
}//if end
}//BFSTraverse() end
- 实现最短路径算法(floyd)
void ShortestPath_FLOYD(MGraph G,
PathMatrix Path[MAX_VERTEX_NUM][MAX_VERTEX_NUM][MAX_VERTEX_NUM],
DistancMatrix Dist[MAX_VERTEX_NUM][MAX_VERTEX_NUM])
{
int i,j,u,v,w;
for(v=0;v
相关文章:
数据结构之栈(C语言版)
数据结构之树的相关问题