图——有向图的深度优先搜索

采用邻接矩阵表示存储有向图


#include

#define MAX_VERTEX_NUM 20

#define INFINITY 32768

#define True 1

#define False 0

#define Error -1

#define OK 1

#include

#pragma warning(disable:4996)

int visited[MAX_VERTEX_NUM]; //访问标志数组
typedef enum { DG, DN, UDG, UDN } GraphKind;
typedef char VertexData;
typedef struct ArcNode {
    int adj; //对于无权图,用1或0表示是否相邻
}ArcNode;
typedef struct {
    VertexData vertex[MAX_VERTEX_NUM]; //顶点向量
    ArcNode arcs[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; //邻接矩阵
    int vexnum, arcnum; // 图的顶点数和弧数
    GraphKind kind;
}AdjMatrix;
int LocateVertex(AdjMatrix *G, VertexData v) {
    int j = Error, k;
    for (k = 0; kvexnum; k++)
         if (G->vertex[k] == v) {
             j= k;
             break;
         }
    return j;
int CreateDG(AdjMatrix *G) {       //创建一个有向图   
    int i, j, k;
    VertexData v1, v2;
    printf("请输入图的顶点数和弧数:");
    scanf("%d,%d", &G->vexnum, &G->arcnum);//输入图的顶点数和弧数	
    for (i = 0; ivexnum; i++)  //初始化邻接矩阵
	for (j = 0; jvexnum; j++)
		G->arcs[i][j].adj= 0;
    getchar();
    printf("请输入所有顶点:\n");
    for (i = 0; ivexnum; i++)
    {
         scanf("%c", &G->vertex[i]);    //输入图的顶点
    }
    printf("输出所有顶点:\n");
    for (i = 0; i <= G->vexnum; i++)
    printf("%c", G->vertex[i]);
    printf("\n");
    printf("请输入一条狐的两个顶点:\n");
    getchar();
    for (k = 0; karcnum; k++) {
         scanf("%c,%c",&v1, &v2);  //输入一条狐的两个顶点
         getchar();
	i= LocateVertex(G, v1);
	j= LocateVertex(G, v2);
	G->arcs[i][j].adj= 1;
    }
    printf("输出邻接矩阵:\n");  //按照矩阵的方式输出邻接矩阵
    for (i = 0; ivexnum; i++)
    {
         for (j = 0; jvexnum; j++)
         {
             printf("%4d", G->arcs[i][j]);
         }
         printf("\n");
    }
    return OK;
}
void DepthFirstSearch(AdjMatrix *G, int v0)
{
    int vj;
    printf("%4c", G->vertex[v0]);
    visited[v0] = True; //访问顶点v0,并置访问标志数组相应分量值
    for (vj = 0; vj < G->vexnum; vj++)
         if (!visited[vj]&& G->arcs[v0][vj].adj == 1)
             DepthFirstSearch(G, vj);
}

void TraverseGraph(AdjMatrix *G) {
    int vi;
    for (vi = 0; vi < G->vexnum; vi++)
         visited[vi]= False; //访问标志数组开始
    for (vi = 0; vi < G->vexnum;vi++)  
    //循环调用深度优先遍历连通子图的操作,若图G是连通图,则此调用只执行一次
         if (!visited[vi])
             DepthFirstSearch(G, vi);
    printf("\n");
}
int main()
{
    AdjMatrix G;
    G.kind= DG;
    CreateDG(&G);
    printf("深度优先搜索图G的结果为:\n");
    TraverseGraph(&G);
    return 0;
}

你可能感兴趣的:(图)