#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxVertexNum 1000
bool Visited[MaxVertexNum]; /**< 记录顶点是否已经被访问了 */
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
/**< 边的定义 */
typedef struct ENode *PtrToENode;
struct ENode
{
Vertex V1, V2;
WeightType Weight;
};
typedef PtrToENode Edge;
/**< 邻接点的定义 */
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode
{
Vertex AdjV;
WeightType Weight;
PtrToAdjVNode Next;
};
typedef PtrToAdjVNode AdjVertex;
/**< 顶点表头结点的定义 */
typedef struct Vnode
{
AdjVertex FirstEdge;
DataType Data;
}AdjList[MaxVertexNum];
/**< 图结点定义 */
typedef struct GNode *PtrToGNode;
struct GNode
{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
LGraph CreateGraph(int VertexNum);
LGraph CreateGraph(int VertexNum)
{
LGraph Graph = (LGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
Vertex V;
for(V=0; V<Graph->Nv; V++)
{
Graph->G[V].FirstEdge = NULL;
Visited[V] = false;
}
return Graph;
}
void InsertEdge(LGraph Graph, Edge E);
void InsertEdge(LGraph Graph, Edge E)
{
/**< 新建邻接点 */
AdjVertex NewNode = (AdjVertex)malloc(sizeof(struct AdjVNode));
NewNode->AdjV = E->V2;
NewNode->Weight = E->Weight;
/**< 将新的邻接点插入v1的顶点表头结点后面*/
NewNode->Next = Graph->G[E->V1].FirstEdge;
Graph->G[E->V1].FirstEdge = NewNode;
/**< 若是无向图,还要加上v2->v1的逆向 */
AdjVertex NewNode1 = (AdjVertex)malloc(sizeof(struct AdjVNode));
/**< 在第一次编写中,没有为逆向的newnode开辟一个新地址,所以导致邻接表是一个死循环 */
NewNode1->AdjV = E->V1;
NewNode1->Weight = E->Weight;
NewNode1->Next = Graph->G[E->V2].FirstEdge;
Graph->G[E->V2].FirstEdge = NewNode1;
}
LGraph BuildGraph();
LGraph BuildGraph()
{
LGraph Graph;
Edge E;
Vertex V;
int Nv, i;
scanf("%d", &Nv);
Graph = CreateGraph(Nv);
scanf("%d", &Graph->Ne);
if(Graph->Ne > 0)
{
E = (Edge)malloc(sizeof(struct ENode));
for(i=0; i<Graph->Ne; i++)
{
scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);
InsertEdge(Graph, E);
}
}
/**<若顶点还有数据,则记录数据 */
for(i=0; i<Graph->Nv; i++)
{
char ch;
while((ch=getchar())==' '||ch=='\n'){};
Graph->G[i].Data = ch;
}
return Graph;
}
void Visit(LGraph Graph, Vertex V);
void Visit(LGraph Graph, Vertex V)
{
printf("%c(%d)\n", Graph->G[V].Data, V);
}
void DFS(LGraph Graph, Vertex V, void(* Visit)(LGraph, Vertex));
void DFS(LGraph Graph, Vertex V, void(* Visit)(LGraph, Vertex))
{
Visited[V] = true;
Visit(Graph, V);
AdjVertex tmpNode;
for(tmpNode = Graph->G[V].FirstEdge; tmpNode; tmpNode = tmpNode->Next)
{
if(!Visited[tmpNode->AdjV])
{
DFS(Graph, tmpNode->AdjV, Visit);
}
}
}
void OneVertex(LGraph Graph, Vertex V)
{
printf("%c(%d)", Graph->G[V].Data, V);
AdjVertex tmpNode;
for(tmpNode=Graph->G[V].FirstEdge; tmpNode; tmpNode = tmpNode->Next)
{
V = tmpNode->AdjV;
printf("->%c(%d)", Graph->G[V].Data, V);
}
}
int main()
{
LGraph g = BuildGraph();
DFS(g, 4, Visit);
//OneVertex(g, 0);
system("pause");
}
邻接表形式的图的深度优先搜索
最新推荐文章于 2025-05-20 16:32:26 发布