# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# include <memory.h>
# define ok 1
# define NULL 0
# define MAX 20 //最大顶点数
typedef struct ARCNODE
{
int adjvex; //该边所指的顶点的位置
struct ARCNODE * next; //指向下一条边的指针
// int weight; //有向图边的权
}arcnode,* node; //表的节点
typedef struct VNODE
{
char data; //顶点信息
node firstarc; //指向第一条依附该顶点的边的弧指针
}vnode,adjlist[MAX]; //头结点
typedef struct algraph
{
adjlist vertices;
int visited[MAX]; //访问标志数组
int vexnum,arcnum; //图的当前顶点数和弧度
}mgraph;
void init_mgraph(mgraph &g) //初始化图
{
memset(g.visited,0,sizeof(int)*MAX); //访问标志数字置0,表示没有被访问
// for (int i=0;i<MAX;++i)
// g.visited[i] = 0;
g.vexnum = 0;
g.arcnum = 0;
}
int locatevex(mgraph &g,char v) //查找顶点v在顶点向量中的位置
{
int i;
for (i=0; v!=g.vertices[i].data && i<g.vexnum; ++i)
;
if (i>=g.vexnum)
return -1;
return i;
}
void add_vex(mgraph &g) //增加节点
{
printf ("请输入无向图的顶点数\n");
scanf ("%d",&g.vexnum);
printf ("输入顶点信息:\n");
for (int i=0;i<g.vexnum;++i)
{
scanf (" %c",&g.vertices[i].data); //构造顶点向量
g.vertices[i].firstarc = NULL;
}
}
void add_arc(mgraph &g) //增加边
{
node s,t;
printf ("请输入无向图的边数\n");
scanf ("%d",&g.arcnum);
char ch1,ch2;
printf ("输入信息\n");
for (int k=0; k<g.arcnum; ++k)
{
scanf (" %c %c",&ch1,&ch2);
int i = locatevex(g,ch1);
int j = locatevex(g,ch2); //确定v1,v2在g中的位置
s = (node)malloc(sizeof(arcnode));
t = (node)malloc(sizeof(arcnode));
s->adjvex = j; //该边所指向的顶点的位置为j
s->next = g.vertices[i].firstarc;
g.vertices[i].firstarc = s;
t->adjvex = i; //该边所指向的顶点的位置为i;
t->next = g.vertices[j].firstarc;
g.vertices[j].firstarc = t;
}
}
void creat_mgraph(mgraph &g) //构造邻接链表
{
add_vex(g); //增加节点
add_arc(g); //增加边
}
void printadjlist(mgraph &g)
{
int i;
node p;
printf ("编号 顶点 邻点编号\n");
for (i=0;i<g.vexnum;++i)
{
printf (" %d %c ",i,g.vertices[i].data);
for (p=g.vertices[i].firstarc;p;p=p->next)
printf ("%d ",p->adjvex);
printf ("\n");
}
}
void visit(mgraph &g,int i)
{
printf ("%c ",g.vertices[i].data);
g.visited[i] = 1;
}
void DFStraverse(mgraph &g,int i) //深度优化搜索
{ //从第i个顶点开始搜索
visit(g,i);
node p;
for ((p=g.vertices[i].firstarc); p ;(p=p->next))
if (!g.visited[p->adjvex])
DFStraverse(g,p->adjvex);
}
int main(void)
{
mgraph g;
init_mgraph(g);
creat_mgraph(g);
printadjlist(g);
DFStraverse(g,0);
return 0;
}
DFS--深度优先搜索--图的邻接表表示
最新推荐文章于 2022-12-19 19:14:31 发布