[PTA] 4-11 Shortest Path [1] (25分)

#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(); 

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;
}

PtrToAdjVNode Insert(PtrToAdjVNode p,int x)
{
	PtrToAdjVNode q;
	q=(PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
	p->Next=q;
	q->AdjV=x;
	q->Next=NULL;
	return q;
}

LGraph ReadG()
{
	int i;
	LGraph p=(LGraph)malloc(sizeof(struct GNode));
	scanf("%d%d",&p->Nv,&p->Ne);
	PtrToAdjVNode rear[MaxVertexNum];
	for(i=0;i<p->Nv;i++){
		p->G[i].FirstEdge=(PtrToAdjVNode)malloc(sizeof(struct AdjVNode));
		rear[i]=p->G[i].FirstEdge;
		rear[i]->Next=NULL;
	}
	for(i=0;i<p->Ne;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		rear[x]=Insert(rear[x],y);
	}
	for(i=0;i<p->Nv;i++){
		PtrToAdjVNode tmp=p->G[i].FirstEdge;
		p->G[i].FirstEdge=p->G[i].FirstEdge->Next;
		free(tmp);
	}
	return p;
}

int queue[MaxVertexNum];
int front,rear;

void enqueue(int x)
{
	front=(front+1)%MaxVertexNum;
	queue[front]=x;
}

int dequeue()
{
	rear=(rear+1)%MaxVertexNum;
	return queue[rear];
}

void ShortestDist( LGraph Graph, int dist[], Vertex S )
{
	front=rear=0;
	int i;
	for(i=0;i<Graph->Nv;i++){
		dist[i]=-1;
	}
	dist[S]=0;
	PtrToAdjVNode p;
	enqueue(S);
	while(rear!=front){
		int v=dequeue();
		p=Graph->G[v].FirstEdge;
		while(p){
			int w=p->AdjV;
			if(dist[w]==-1){
				dist[w]=dist[v]+1;
				enqueue(w);
			}
			p=p->Next;
		}
	}
}

你可能感兴趣的:([PTA] 4-11 Shortest Path [1] (25分))