圖的鄰接表演算法---(附完整程式碼)

玥娃娃發表於2018-08-15

1.鄰接表的資料結構

2.初始化有頂點沒有邊的圖

3.插入邊

4.建立圖

5.鄰接表儲存圖的深度優先遍歷DFS

#include<stdio.h>
#include<stdlib.h>
#define MaxVertexNum 100
typedef int Vertex;
typedef int WeightType;
typedef char DataType;
bool Visited[]={false};

//邊的定義
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 struct Vnode{
	PtrToAdjVNode FirstEdge;
	DataType Data;
}AdjList[MaxVertexNum]; 

//圖結點的定義 
typedef struct GNode * PtrToGNode;
struct GNode {
	int Nv;			//定點數 
	int Ne;			//邊數 
	AdjList G;		//鄰接表 
}; 
typedef PtrToGNode LGraph;

//初始化一個有VertexNum個頂點但沒有邊的圖
LGraph CreateGraph(int VertexNum){
	Vertex V;
	LGraph Graph;
	
	Graph=(LGraph)malloc(sizeof(struct GNode));
	Graph->Nv=VertexNum;
	Graph->Ne=0;
	
	//初始化鄰接表頭指標
	for(V=0;V<Graph->Nv;V++)
		Graph->G[V].FirstEdge=NULL;
	return Graph; 
} 

//插入邊
void InsertEdge(LGraph Graph,Edge E){
	PtrToAdjVNode NewNode;
	
	NewNode=(PtrToAdjVNode)malloc (sizeof(struct AdjVNode));
	NewNode->AdjV=E->V2;
	NewNode->Weight=E->Weight;
	NewNode->Next=Graph->G[E->V1].FirstEdge;
	Graph->G[E->V1].FirstEdge=NewNode;
	
	//若是無向圖,還要插入邊<V2,V1>
	//位V1建立新的鄰接點
	NewNode=(PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
	NewNode->AdjV=E->V1;
	NewNode->Weight=E->Weight;
	//將V1插入V2的表頭
	NewNode->Next=Graph->G[E->V2].FirstEdge;
	Graph->G[E->V2].FirstEdge=NewNode; 
} 

LGraph BuildGraph(){
	LGraph Graph;
	Edge E;
	Vertex V;
	int Nv,i;
	
	printf("請輸入頂點個數\n");
	scanf("%d",&Nv);
	Graph=CreateGraph(Nv);
	
	printf("讀入邊數\n");
	scanf("%d",&(Graph->Ne));
	if(Graph->Ne!=0){//如果有邊 
		E=(Edge)malloc(sizeof(struct ENode));
		for(i=0;i<Graph->Ne;i++){
			printf("讀入邊,格式為“起點 終點 權重”:\n ");
			scanf("%d %d %d",&E->V1,&E->V2,&E->Weight);
			InsertEdge(Graph,E);
		}
	}
	
	//如果頂點有資料的話,讀入資料
	//for(V=0;V<Graph->Nv;V++)
	//	scanf("%c",&(Graph->G[V].Data));
	
	return Graph; 
}

//鄰接表儲存圖的深度優先遍歷
void Visit(Vertex V){
	printf("正在訪問頂點%d\n",V);
} 

void DFS(LGraph Graph,Vertex V,void(*Visit)(Vertex)){
	PtrToAdjVNode W;
	
	Visit(V);
	Visited[V]=true;
	
	for(W=Graph->G[V].FirstEdge;W;W=W->Next){
		if(!Visited[W->AdjV])
			DFS(Graph,W->AdjV,Visit);
	}
}

int main()
{
	LGraph Graph;
	Graph = BuildGraph();
	int v=0;
	DFS(Graph,v,Visit);
	return 0;
}

執行結果:

相關文章