Chapter 9 Graph (2)

Dijkstra算法实现

/*伪码描述:
void Dijkstra(Graph G,Table T)
{
     Vertex V,W;
     
     for(; ;)
     {
         V = smallst unknown distance vertex;
	 if(V == NotAVertex)
	    break;
	  T[V].konwn = ture;
	  for each W adjancent to V;
	  if(!T[W}.konwn)
	     if(T[V].dis + Cvw < T[W].dis)
	     {
	        Decrease(T[W].dis to T[V}.dis + Cvw);
		T[W].path = V;
	      }
        }
}
*/
	 

#include <stdio.h>
#include <stdlib.h>

#define MaxVertexNum 100
#define INFINITY 65535

typedef int DistType;
typedef int Vertex;
typedef int WeightType;     //边的权值设为整数
typedef char DataType;      //顶点的数据存储
typedef int ElementType;
typedef struct QueueRecord
{
	int Front;
	int Rear;
	int Capacity;
	ElementType *Array;
}*Queue;

void InitQueue(Queue Q)
{
	Q->Front = 0;
	Q->Rear = 0;
}

Queue CreatQueue(int MaxSize)
{
	Queue Q = (QueueRecord*)malloc(sizeof(QueueRecord));
	Q->Capacity = MaxSize;
	Q->Array = (ElementType*)malloc(sizeof(ElementType) * MaxSize);
	InitQueue(Q);
	return Q;
}

int Enqueue(Queue Q, ElementType X)
{
	if ((Q->Rear + 1) % Q->Capacity == Q->Front)
		return -1;
	Q->Rear = (Q->Rear + 1) % Q->Capacity;
	Q->Array[Q->Rear] = X;
	return 0;
}

ElementType Dequeue(Queue Q)
{
	if (Q->Front == Q->Rear)
		return -1;
	Q->Front = (Q->Front + 1) % Q->Capacity;
	return Q->Array[Q->Front];
}

//边的定义
typedef struct ENode
{
	Vertex V1, V2;       //边的两个顶点
	WeightType Weight;   //边的权重
}*Edge;

//图的结点定义
typedef struct GNode
{
	int Nv;         //顶点数
	int Ne;         //边数
	WeightType Weight[MaxVertexNum][MaxVertexNum];   //邻接矩阵
	DataType Data[MaxVertexNum];     //存顶点的数据
}*MGraph;

//初始化一个图
MGraph CreateGraph(int VertexNum)
{
	//初始化一个有VertexNum个结点但没有边的图
	Vertex V, W;
	MGraph Graph;

	Graph = (MGraph)malloc(sizeof(GNode));  //建立图
	Graph->Nv = VertexNum;
	Graph->Ne = 0;

	//初始化邻接矩阵,将权重置为∞
	for (V = 0; V <= Graph->Nv; V++)
		for (W = 0; W <= Graph->Nv; W++)
			Graph->Weight[V][W] = INFINITY;

	return Graph;
}

//边的插入
void InsertEdge(MGraph Graph, Edge E)
{
	Graph->Weight[E->V1][E->V2] = E->Weight;
}

//构建一个图
MGraph BuildGraph()
{
	MGraph Graph;
	Edge E;
	Vertex V;
	int Nv, i;

	scanf("%d", &Nv);      //读入顶点个数
	Graph = CreateGraph(Nv);  //初始化一个有VertexNum个结点但没有边的图

	scanf("%d", &(Graph->Ne));  //读入边数
	if (Graph->Ne != 0)         //如果有边
	{
		E = (Edge)malloc(sizeof(ENode));  //建立边结点
										  //读入边,格式为“起点”,“终点”,“权重”
		for (i = 0; i < Graph->Ne; i++)
		{
			scanf("%d %d %d", &E->V1, &E->V2, &E->Weight);
			InsertEdge(Graph, E);   //插入边
		}
	}

	return Graph;
}

typedef struct TableNode
{
	int Known;
	DistType Distence;
	Vertex Path;
}Table;


void InitTable(Vertex Start, MGraph Graph, Table *T)
{
	int i;
	for (i = 0; i <= Graph->Nv; i++)
	{
		T[i].Distence = INFINITY;
		T[i].Known = 0;
		T[i].Path = 0;
	}
	T[Start].Distence = 0;
}

Vertex FindMinDist(MGraph Graph, Table *T)
{
	Vertex MinV, V;
	int MinDist = INFINITY;

	for (V = 0; V <= Graph->Nv; V++)
	{
		if (T[V].Known == 0 && T[V].Distence < MinDist)
		{
			MinDist = T[V].Distence;
			MinV = V;
		}
	}
	if (MinDist < INFINITY)
		return MinV;
	else
		return 0;
}

void PrintPath(Vertex V, Table *T)
{
	if (T[V].Path != 0)
	{
		PrintPath(T[V].Path, T);
		printf("to ");       //递归出口
	}
	printf("V%d ", V);
}

void Dijkstra(MGraph Graph, Table *T)
{
	Vertex V, W;
	for (;;)
	{
		V = FindMinDist(Graph, T);
		if (V == 0)
			break;
		T[V].Known = 1;
   		for (W = 0; W <= Graph->Nv; W++)
		{
			if(Graph->Weight[V][W] != INFINITY && T[W].Known == 0)
				if (T[V].Distence + Graph->Weight[V][W] < T[W].Distence)
				{
					T[W].Distence = T[V].Distence + Graph->Weight[V][W];
					T[W].Path = V;
				}
		}
	}
}

int main()
{
	MGraph Graph = BuildGraph();
	Table T[MaxVertexNum];
	InitTable(1,Graph,T);
	Dijkstra(Graph, T);
	Vertex V;
	for (V = 1; V <= Graph->Nv; V++)
	{
		printf("The distence of V%d is %d,and the path is ", V,T[V].Distence);
		PrintPath(V, T);
		printf("\n");
	}
	
}
/*
7 12
3 1 4
1 2 2
2 5 10
5 7 6
7 6 1
3 6 5
4 3 2
1 4 1
2 4 3
4 5 2
4 7 4
4 6 8
*/

无权图的最短路径

#include <stdio.h>
#include <stdlib.h>
#define MaxVertexNum 100
#define INFINITY 65535

typedef int DistType;
typedef int Vertex;
typedef int WeightType;     //边的权值设为整数
typedef char DataType;      //顶点的数据存储
typedef int ElementType;
typedef struct QueueRecord
{
	int Front;
	int Rear;
	int Capacity;
	ElementType *Array;
}*Queue;

void InitQueue(Queue Q)
{
	Q->Front = 0;
	Q->Rear = 0;
}

Queue CreatQueue(int MaxSize)
{
	Queue Q = (QueueRecord*)malloc(sizeof(QueueRecord));
	Q->Capacity = MaxSize;
	Q->Array = (ElementType*)malloc(sizeof(ElementType) * MaxSize);
	InitQueue(Q);
	return Q;
}

int Enqueue(Queue Q, ElementType X)
{
	if ((Q->Rear + 1) % Q->Capacity == Q->Front)
		return -1;
	Q->Rear = (Q->Rear + 1) % Q->Capacity;
	Q->Array[Q->Rear] = X;
	return 0;
}

ElementType Dequeue(Queue Q)
{
	if (Q->Front == Q->Rear)
		return -1;
	Q->Front = (Q->Front + 1) % Q->Capacity;
	return Q->Array[Q->Front];
}

//边的定义
typedef struct ENode
{
	Vertex V1, V2;        //有向边<V1,V2>
}*Edge;

//邻接点的定义
typedef struct AdjVNode
{
	Vertex AdjV;           //邻接点下标
	struct AdjVNode *Next; //指向下一邻接点的指针
}*PtrToAdjVNode;

//顶点表头结点的定义
typedef struct VNode
{
	PtrToAdjVNode FirstEdge;   //边表头指针
	DataType Data;             //存顶点的数据
}AdjList[MaxVertexNum];        //AdjList是邻接表类型

							   //图结点的定义
typedef struct GNode
{
	int Nv;     //顶点数
	int Ne;     //边数
	AdjList G;  //邻接表
}*LGraph;       //以邻接表方式存储图类型

				//初始化邻接表图
LGraph CreateGraph(int VertexNum)
{
	Vertex V;
	LGraph Graph;

	Graph = (LGraph)malloc(sizeof(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;

	//插入边<V1,V2>
	//为V2建立新的邻接点
	NewNode = (PtrToAdjVNode)malloc(sizeof(AdjVNode));
	NewNode->AdjV = E->V2;
	//将V2插入V1的表头
	NewNode->Next = Graph->G[E->V1].FirstEdge;
	Graph->G[E->V1].FirstEdge = NewNode;
}

//创建一个邻接表图
LGraph BuildGraph()
{
	LGraph Graph;
	Edge E;
	Vertex V;
	int Nv, i;

	scanf("%d", &Nv);          //读入顶点个数
	Graph = CreateGraph(Nv);   //初始化有Nv个顶点但没有边的图

	scanf("%d", &Graph->Ne);   //读入边数
	if (Graph->Ne != 0)        //如果有边
	{
		E = (Edge)malloc(sizeof(ENode)); //建立边结点
		for (i = 0; i < Graph->Ne; i++)
		{
			//读入边,格式为“起点”,“终点”,“权重”
			scanf("%d %d", &E->V1, &E->V2);
			InsertEdge(Graph, E);
		}
	}

	return Graph;
}
typedef struct TableNode
{
	int Known;
	DistType Distence;
	Vertex Path;
}Table;


void InitTable(Vertex Start, LGraph Graph, Table *T)
{
	int i;
	for (i = 0; i <= Graph->Nv; i++)
	{
		T[i].Distence = INFINITY;
		T[i].Known = 0;
		T[i].Path = 0;
	}
	T[Start].Distence = 0;
}

void Unweighted(Table *T, LGraph Graph, Vertex S)
{
	Queue Q;
	Q = CreatQueue(Graph->Nv);
	InitQueue(Q);
	Vertex V;

	Enqueue(Q, S);   //将初始点S入队

	while (Q->Front != Q->Rear)    //队列非空
	{
		V = Dequeue(Q);        //将一个结点出队
		T[V].Known = 1;        //标记该结点

		PtrToAdjVNode W;
		//遍历当前结点的所有邻接点
		for (W = Graph->G[V].FirstEdge; W; W = W->Next)
		{
			if (T[W->AdjV].Distence == INFINITY)
			{
				T[W->AdjV].Distence = T[V].Distence + 1;
				T[W->AdjV].Path = V;
				Enqueue(Q, W->AdjV);
			}
		}
	}
}

//测试函数
int main()
{
	LGraph Graph = BuildGraph();
	Table  T[MaxVertexNum];
	InitTable(3, Graph, T);

	Unweighted(T, Graph, 3);

	Vertex V;
	for (V = 1; V <= Graph->Nv; V++)
		printf("%d ", T[V].Distence);
}

拓扑排序

#include <stdio.h>
#include <stdlib.h>

#define MaxVertexNum 100    //最大顶点数设为100
typedef int Vertex;         //用顶点下标表示顶点
typedef int WeightType;     //边的权值设为整数
typedef char DataType;      //顶点的数据存储

							//边的定义
typedef struct ENode
{
	Vertex V1, V2;        //有向边<V1,V2>
	WeightType Weight;    //权重
}*Edge;

//邻接点的定义
typedef struct AdjVNode
{
	Vertex AdjV;           //邻接点下标
	WeightType Weight;     //边权重
	struct AdjVNode *Next; //指向下一邻接点的指针
}*PtrToAdjVNode;

//顶点表头结点的定义
typedef struct VNode
{
	PtrToAdjVNode FirstEdge;   //边表头指针
	DataType Data;             //存顶点的数据
}AdjList[MaxVertexNum];        //AdjList是邻接表类型

							   //图结点的定义
typedef struct GNode
{
	int Nv;     //顶点数
	int Ne;     //边数
	AdjList G;  //邻接表
}*LGraph;       //以邻接表方式存储图类型

				//初始化邻接表图
LGraph CreateGraph(int VertexNum)
{
	Vertex V;
	LGraph Graph;

	Graph = (LGraph)malloc(sizeof(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;

	//插入边<V1,V2>
	//为V2建立新的邻接点
	NewNode = (PtrToAdjVNode)malloc(sizeof(AdjVNode));
	NewNode->AdjV = E->V2;
	NewNode->Weight = E->Weight;
	//将V2插入V1的表头
	NewNode->Next = Graph->G[E->V1].FirstEdge;
	Graph->G[E->V1].FirstEdge = NewNode;

	//若是无向图,还要插入边<V2,V1>
	//为V1建立新的邻接点
	/*NewNode = (PtrToAdjVNode)malloc(sizeof(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;

	scanf("%d", &Nv);          //读入顶点个数
	Graph = CreateGraph(Nv);   //初始化有Nv个顶点但没有边的图

	scanf("%d", &Graph->Ne);   //读入边数
	if (Graph->Ne != 0)        //如果有边
	{
		E = (Edge)malloc(sizeof(ENode)); //建立边结点
		for (i = 0; i < Graph->Ne; i++)
		{
			//读入边,格式为“起点”,“终点”,“权重”
			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;
}

typedef int ElementType;
typedef struct QueueRecord
{
	int Front;
	int Rear;
	int Capacity;
	ElementType *Array;
}*Queue;

void InitQueue(Queue Q)
{
	Q->Front = 0;
	Q->Rear = 0;
}

Queue CreatQueue(int MaxSize)
{
	Queue Q = (QueueRecord*)malloc(sizeof(QueueRecord));
	Q->Capacity = MaxSize;
	Q->Array = (ElementType*)malloc(sizeof(ElementType) * MaxSize);
	InitQueue(Q);
	return Q;
}

int Enqueue(Queue Q, ElementType X)
{
	if ((Q->Rear + 1) % Q->Capacity == Q->Front)
		return -1;
	Q->Rear = (Q->Rear + 1) % Q->Capacity;
	Q->Array[Q->Rear] = X;
	return 0;
}

ElementType Dequeue(Queue Q)
{
	if (Q->Front == Q->Rear)
		return -1;
	Q->Front = (Q->Front + 1) % Q->Capacity;
	return Q->Array[Q->Front];
}

// 对Graph进行拓扑排序,  TopOrder[]顺序存储排序后的顶点下标
bool TopSort( LGraph Graph, Vertex TopOrder[] )
{  
    int Indegree[MaxVertexNum], Index;
    Vertex V;
    PtrToAdjVNode W;
       Queue Q = CreatQueue( Graph->Nv );
  
    // 初始化Indegree[]
    for (V=0; V<Graph->Nv; V++)
        Indegree[V] = 0;
         
    // 遍历图,得到Indegree[]
    for (V=0; V<Graph->Nv; V++)
        for (W=Graph->G[V].FirstEdge; W; W=W->Next)
            Indegree[W->AdjV]++; // 对有向边<V, W->AdjV>累计终点的入度
             
    // 将所有入度为0的顶点入列
    for (V=0; V<Graph->Nv; V++)
        if ( Indegree[V]==0 )
            Enqueue(Q, V);
             
    // 下面进入拓扑排序 
    Index = 0; 
    while( Q->Front != Q->Rear){
        V = Dequeue(Q);       // 弹出一个入度为0的顶点
        TopOrder[Index++] = V; // 将之存为结果序列的下一个元素
        // 对V的每个邻接点W->AdjV
        for ( W=Graph->G[V].FirstEdge; W; W=W->Next )
            if ( --Indegree[W->AdjV] == 0 )   // 若删除V使得W->AdjV入度为0 
                Enqueue(Q, W->AdjV);          // 则该顶点入列 
    } 
     
    if ( Index != Graph->Nv )
        return false; // 说明图中有回路, 返回不成功标志 
    else
        return true;
}

//测试函数
int main()
{
	LGraph Graph = BuildGraph();
	Vertex Top[MaxVertexNum];
	TopSort(Graph, Top);
	for (Vertex V = 0; V < Graph->Nv; V++)
		printf("%d ", Top[V]);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值