데이터 구조 - 최 단 경로 알고리즘 요약 (중국 대학 mooc)

21234 단어 DataStructure
//         
//BFS
//dist[W]:S W    
//path[W]:S W        
//dist path      -1
void Unweighted(LGraph Graph,int dist[],int path[],Vertex S){
    Queue Q;
    Vertex V;
    PtrToAdjNode W;
    Q = CreateQueue(Graph->Nv);
    dist[S] = 0//     ,  0
    AddQ(Q,S);
    while(!IsEmpty(Q)){
        V = DeleteQ(Q);
        for(W = Graph->G[V].FirstEdge;W;W = W->Next){
            if(dist[W->AdjV]==-1){
                dist[W->AdjV] = dist[V] + 1;
                path[W->AdjV] = V;
                AddQ(Q,W->AdjV);
            }
        }
    }
}
//         Dijkstra

//         dist   
Vertex FindMinDist(MGraph Graph,int dist[],int collected[]){
    Vertex MinV,V;
    int MinDist = INFINITY;
    for(V = 0;V<Graph->Nv;V++){
        if(collected[V] == false && dist[V]<MinDist){
            MinDist = Dist[V];
            MinV = V;
        }
    }
    if(MinDist < INFINITY){
        return MinV;
    }
    else{
        return ERROR;
    }
}
bool Dijkstra(MGraph Graph,int Dist[],int path[],Vertex S){
    int collected[MaxVertexNum];
    Vertex V,W;
    for(V=0;V<Graph->Nv;V++){
        dist[V] = Graph->G[S][V];
        if(dist[V]<INFINITY){
            path[V] = S;
        }
        else{
            path[V] = -1;
        }
        collected[V] = false;
    }
    dist[S] = 0;
    collected[S] = true;
    while(1){
        V = FindMinDist(Graph,dist,collected);
        if(V==ERROR){
            break;
        }
        collected[V] = true;
        for(W=0;W<Graph->Nv;W++){
            if(collected[V]==false && Graph->G[V][W] < INFINITY){
                if(Graph->G[V][W]<0){
                    return false;
                }
                if(dist[V]+Graph->G[V][W]<dist[W]){
                    dist[W] = dist[V] + Graph->G[V][W];
                    path[W] = V;
                }
            }
        }
    }
    return true;
}

//      Floyd
bool Floyd(MGraph Graph,WeightType D[][MaxVertexNum],Vertex path[][MaxVertexNum]){
    Vertex i,j,k;
    for(i=0;i<Graph->Nv;i++){
        for(j=0;j<Graph->Nv;j++){
            D[i][j] = Graph->G[i][j];
            path[i][j] = -1;
        }
    }
    for(k=0;k<Graph->Nv;k++){
        for(i=0;i<Graph->Nv;i++){
            for(j=0;j<Graph->Nv;j++){
                if(D[i][k] + D[k][j] < D[i][j]){
                    D[i][j] = D[i][k] + D[k][j];
                    if(i==j && D[i][j]<0){
                        return false;
                    }
                    path[i][j] = k;
                }
            }
        }
    }
    return true;
}

좋은 웹페이지 즐겨찾기