bool Dijkstra( MGraph Graph, int dist[], int path[], Vertex S )
{
    int collected[MaxVertexNum];
    Vertex V, W;
 
    /* 初始化:此处默认邻接矩阵中不存在的边用INFINITY表示 */
    for ( V=0; V<Graph->Nv; V++ ) {
        dist[V] = Graph->G[S][V];
        path[V] = -1;
        collected[V] = false;
    }
    /* 先将起点收入集合 */
    dist[S] = 0;
    collected[S] = true;
 
    while (1) {
        /* V = 未被收录顶点中dist最小者 */
        V = FindMinDist( Graph, dist, collected );
        if ( V==ERROR ) /* 若这样的V不存在 */
            break;      /* 算法结束 */
        collected[V] = true;  /* 收录V */
        for( W=0; W<Graph->Nv; W++ ) /* 对图中的每个顶点W */
            /* 若W是V的邻接点并且未被收录 */
            if ( collected[W]==false && Graph->G[V][W]<INFINITY ) {
                if ( Graph->G[V][W]<0 ) /* 若有负边 */
                    return false; /* 不能正确解决,返回错误标记 */
                /* 若收录V使得dist[W]变小 */
                if ( dist[V]+Graph->G[V][W] < dist[W] ) {
                    dist[W] = dist[V]+Graph->G[V][W]; /* 更新dist[W] */
                    path[W] = V; /* 更新S到W的路径 */
                }
            }
    } /* while结束*/
    return true; /* 算法执行完毕,返回正确标记 */
}
Esempio n. 2
0
TilePath clPather::RunBase()
{
    TilePath ret;
    if(FindVertex(en,graph)==-1) return ret;
    int stpos=FindVertex(st,graph);
    if(stpos==-1)return ret;
    graph[stpos]->dist=0;
    std::vector <TileVertex*> Q;
    Q=graph;
    while(Q.size()>0)
    {
        int pos=FindMinDist(Q);
        TileVertex *u=Q[pos];

        if(u->a==en) //yeah cia bisky pagreitinimas...
        {
            Q.clear();
            break;
        }

        Q.erase(Q.begin()+pos);
        for(int i=E_UP;i<E_LAST;i++)
        {
            int vind=FindVertex(u->a->GetSide((SIDES)i),Q);
            //int vind=FindVertex(u->a->GetSide((SIDES)i),graph);
            unsigned alt=u->dist+1;
            if(vind!=-1)
            {
                TileVertex *v=Q[vind];
                if(alt<v->dist)
                {
                    v->dist=alt;
                    v->prev=u;
                }
            }
        }
    }
    TileVertex *cur=graph[FindVertex(en,graph)];
    while(cur->prev!=NULL)
    {
    ret.push_back(cur->a);
    cur=cur->prev;
    }

    for(int i=0;i<graph.size();i++)
        delete graph[i];
    graph.clear();
    return ret;
}