图创建和相关操作:
#define MAX_VETEX_NUM 20
#define ERROR 0
#include <iostream.h>
#include <malloc.h>
typedef struct ArcNode
{
int adjvex;//当前节点顶点
struct ArcNode *nextarc;//指向相关节点的指针
int info;//权信息
}ArcNode;
typedef struct VNode
{
int data;//图的当前信息
ArcNode *firstarc;//指向第一条依附该节点的信息
}VNode,AdjList[MAX_VETEX_NUM];
typedef struct
{
AdjList vertices;
int vexnum,arcnum;//ͼµÄµ±Ç°¶¥µãÊýºÍ»¡Êý
int kind ;//ͼµÄÖÖÀà±êÖ¾
}ALGraph;
void InitALGraph(ALGraph &g)
{
int i;
//g=(ALGraph *)malloc(sizeof(ALGraph));
cout<<"input the vertices and arc numbers :";
cin>>g.vexnum>>g.arcnum;
//the information of the vertices
for (i=1;i<=g.vexnum;i++)
{
cout<<"the order "<<i<< " data information:";
cin>>g.vertices[i].data;
}
for (i=1;i<=g.vexnum;i++)
{
g.vertices[i].firstarc=NULL;
g.kind=0;//undireced graph
}
}
// int LocateVex(ALGraph &g,int u)
// {
// if (u<g.vexnum)
// {
// return ERROR;
// }
// for (int i=0;i<g.vexnum;i++)
// {
//
// }
// }
void CreateGraph(ALGraph &g)
{
int i,s,e,w;
ArcNode *p;
//initial graph
InitALGraph(g);
for (i=1;i<=g.arcnum;i++)
{
cout<<"the order "<<i<<"arc the start arc ,the end arc and the weight:";
cin>>s>>e>>w;
p=(ArcNode*)malloc(sizeof(ArcNode));
p->adjvex=e;
p->info=w;
p->nextarc=g.vertices[s].firstarc;
g.vertices[s].firstarc=p;
}
}
void DisplayGraph(ALGraph &g)
{
int i;
ArcNode *p;
cout<<"the graph is :"<<endl;
for (i=1;i<=g.vexnum;i++)
{
cout<<"vetex["<<i<<"]: ("<<g.vertices[i].data<<")-->";
p=g.vertices[i].firstarc;
while (p!=NULL)
{
cout<<"("<<p->adjvex<<","<<p->info<<")-->";
p=p->nextarc;
}
cout<<"^"<<endl;
}
}
//next of the vertex n
int NextVertex(ALGraph &g,int n)
{
if (n==g.vexnum-1)
{
return ERROR;
}
else
{
return n+1;
}
}
//return the i's firstadjacent
int FirstAdjacent(ALGraph &g,int i)
{
ArcNode *p;
p=g.vertices[i].firstarc;
if (p!=NULL)
{
return p->adjvex;
}
else
{
return ERROR;
}
}
//return the next adjacent of j that is in the list of vertex n
int NextAdjacent(ALGraph g,int n,int j)
{
ArcNode *p;
for (p=g.vertices[n].firstarc;p!=NULL;p=p->nextarc)
{
if (p->adjvex==j)
{
if (p->nextarc!=NULL)
{
return p->nextarc->adjvex;
}
else return 0;
}
}
return 0;
}
//dfs(deep_first )
void DFS(ALGraph g,int v)
{
int w;
visited[v]=true;
cout<<v<<" ";
for (w=FirstAdjacent(g,v);w>=1;w=NextAdjacent(g,v,w))
{
if (!visited[w])
{
DFS(g,w);
}
}
}
void DFSTraverse(ALGraph g)
{
//initial the visited array
int i;
for (i=1;i<=g.vexnum;i++)
visited[i]=false;
for (i=1;i<=g.vexnum;i++)
{
if (!visited[i])
{
DFS(g,i);
}
}
}
调用主程序:
#include "graph.h"
void main()
{
ALGraph g;
char n;
CreateGraph(g);
DisplayGraph(g);
cout<<"the i's vertex adjacent is :"<<FirstAdjacent(g,1);
DFSTraverse(g);
}