#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 10
//定义图结构
typedef struct GMap
{
char vertex[MAXSIZE]; //存放顶点数组
int ace[MAXSIZE][MAXSIZE]; //邻接矩阵
int vexnum; //顶点数
int acenum; //边数
};
void DFStraverse(GMap*, int);
void WFStraverse(GMap*, int);
void delace(GMap*, int, int);
void addace(GMap*, int, int);
void delvex(GMap*);
void addvex(GMap*, char);
void ini(GMap*, char a[], int);
void disply_ace(GMap*);
void display_vex(GMap*);
void main()
{
GMap* t = (GMap*)malloc(sizeof(GMap));
char a[5] = {‘a’,’b’,’c’,’d’,’e’};
ini(t, a, 5);
addace(t, 0, 1);
addace(t, 0, 2);
addace(t, 1, 3);
addace(t, 0, 3);
addace(t, 3, 4);
display_vex(t);
disply_ace(t);
WFStraverse(t, 0);
printf(“/n/n”);
DFStraverse(t, 0);
free(t);
}
/*————————————–
//广度优先遍历,顺序打印出来
t为图指针,
v为开始顶点索引
—————————————*/
void WFStraverse(GMap* t, int v)
{
int visit[MAXSIZE] = {0};
int seq[MAXSIZE];
int front = -1; //队头初始化
int rear = -1; //队尾初始化
seq[++rear] = v;
printf(“/n/n”);
printf(“%c “, t->vertex[v]);
visit[v] = 1; //开始遍历的初始节点设置成已访问过
while ( front != rear ) //遍历是否完成的判断条件,队列是否为空
{
v = seq [++front];
for (int i = 0; i < t->vexnum; i++)
{
if (t->ace[v][i] == 1 && visit[i] == 0)
{
printf(“%c “, t->vertex[i]);
visit[i] = 1; //每遍历一个顶点就将该顶点设置为已访问过
seq[++rear] = i; //每遍历一个顶点就将该顶点入队
}
}
}
printf(“/n/n”);
}
/*———————————-
/深度优先遍历,顺序打印出来
t:图指针
v:顶点在数组中的索引值
———————————–*/
void DFStraverse(GMap* t, int v)
{
static int visit[MAXSIZE] = { 0 }; //注意:该处设置成static类型
printf(“%c “, t->vertex[v]);
visit[v] = 1;
for ( int j = 0; j < t->vexnum; j++)
{
if (t->ace[v][j] == 1 && visit[j] == 0)
{
DFStraverse( t, j ); //递归方法
}
}
}
//删除边,删除存在于顶点x、y之间的边
void delace(GMap* t, int x, int y)
{
t->ace[x][y] = 0;
t->ace[y][x] = 0;
t->acenum = t->acenum – 1;
}
//添加边,添加顶点x到y的边
void addace(GMap* t, int x, int y)
{
t->ace[x][y] = 1;
t->ace[y][x] = 1;
t->acenum = t->acenum + 1;
}
//删除顶点
void delvex(GMap*, int x)
{
}
//显示边
void disply_ace(GMap* t)
{
for ( int i = 0; i < t->vexnum; i++)
{
for ( int j = 0; j < t->vexnum; j++)
{
printf(“%d “, t->ace[i][j]);
}
printf(“/n”);
}
printf(“/n/n”);
}
//显示顶点
void display_vex(GMap* t)
{
for ( int i = 0; i < t->vexnum; i++)
{
printf(“%c “, t->vertex[i]);
}
printf(“/n/n”);
}
//初始化图
void ini(GMap* t, char a[], int n)
{
for ( int i = 0; i < n; i++)
{
t->vertex[i] = a[i];
}
for ( int x = 0; x < n; x++)
{
for ( int y = 0; y < n; y++)
{
t->ace[x][y] = 0;
}
}
t->vexnum = n;
t->acenum = 0;
}