Write a program to find the unweighted shortest distances from any vertex to a given source vertex in a digraph.( 编写一个程序,找出有向图中从任何顶点到给定源顶点的未加权最短距离。)
函数接口定义:
void ShortestDist( LGraph Graph, int dist[], Vertex S );
where LGraph is defined as the following:
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
The shortest distance from V to the source S is supposed to be stored in dist[V]. If V cannot be reached from S, store -1 instead.(从V到源S的最短距离应该存储在dist[V]中。如果无法从S到达V,则存储-1。)
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef enum {false, true} bool;
#define MaxVertexNum 10 /* maximum number of vertices */
typedef int Vertex; /* vertices are numbered from 0 to MaxVertexNum-1 */
typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;
LGraph ReadG(); /* details omitted */
void ShortestDist( LGraph Graph, int dist[], Vertex S );
int main()
{
int dist[MaxVertexNum];
Vertex S, V;
LGraph G = ReadG();
scanf("%d", &S);
ShortestDist( G, dist, S );
for ( V=0; V<G->Nv; V++ )
printf("%d ", dist[V]);
return 0;
}
/* Your function will be put here */
输入样例:
7 9
0 1
0 5
0 6
5 3
2 1
2 6
6 4
4 5
6 5
2
输出样例:
-1 1 0 3 2 2 1
代码:
int vis[MaxVertexNum];
void ShortestDist( LGraph Graph, int dist[], Vertex S )//无权有向图,邻接表
{
//初始化dist[]和vis[]
for(int i=0;i<Graph->Nv;i++)
{
dist[i]=100;//初始化路径为无穷大
vis[i]=0;
}
//标记S点的邻接点
vis[S]=1;
dist[S]=0;
PtrToAdjVNode p=Graph->G[S].FirstEdge;
while(p)
{
dist[p->AdjV]=1;//S点的邻接点路径都+1
p=p->Next;
}
//找不到v点时退出循环
while(1)
{
int v=-1;
int min=100;
//可以通过找v点来实现每个点都遍历一遍
for(int j=0;j<Graph->Nv;j++)
{
if(vis[j]==0&&dist[j]<min)//v点满足两个条件:没被访问过和路径最短
{
min=dist[j];
v=j;
}
}
if(v==-1) break;//未找到v点
vis[v]=1;//访问v点
p=Graph->G[v].FirstEdge;//访问v点的每个邻接点
while(p)
{
//邻接点没被访问过且路径比v点大,更新邻接点路径
if(vis[p->AdjV]==0&&dist[v]+1<dist[p->AdjV])
dist[p->AdjV]=dist[v]+1;
p=p->Next;
}
}
//如果路径为无穷大的点表示S点不能到达该点
for(int i=0;i<Graph->Nv;i++)
{
if(dist[i]==100) dist[i]=-1;
}
}