未加权的最短路径

时间:2011-05-11 19:28:44

标签: java ruby-on-rails data-structures

如何找到具有最短加权路径的最短未加权路径...例如,如果我有两个未加权路径A-> B-> C = 2且A-> D-> F = 2 ....如何打印加权路径较少的那个?

未加权和加权路径的代码如下:

public void unweighted( String startName )
{
    clearAll( ); 

    Vertex start = vertexMap.get( startName );
    if( start == null )
        throw new NoSuchElementException( "Start vertex not found" );

    Queue<Vertex> q = new LinkedList<Vertex>( );
    q.add( start ); start.dist = 0;

    while( !q.isEmpty( ) )
    {
        Vertex v = q.remove( );

        for( Edge e : v.adj )
        {
            Vertex w = e.dest;
            if( w.dist == INFINITY )
            {
                w.dist = v.dist + 1;
                w.prev = v;
                q.add( w );
            }
        }
    }
}

加权:

public void dijkstra( String startName )
{
    PriorityQueue<Path> pq = new PriorityQueue<Path>( );

    Vertex start = vertexMap.get( startName );
    if( start == null )
        throw new NoSuchElementException( "Start vertex not found" );

    clearAll( );
    pq.add( new Path( start, 0 ) ); start.dist = 0;

    int nodesSeen = 0;
    while( !pq.isEmpty( ) && nodesSeen < vertexMap.size( ) )
    {
        Path vrec = pq.remove( );
        Vertex v = vrec.dest;
        if( v.scratch != 0 )  // already processed v
            continue;

        v.scratch = 1;
        nodesSeen++;

        for( Edge e : v.adj )
        {
            Vertex w = e.dest;
            double cvw = e.cost;

            if( cvw < 0 )
                throw new GraphException( "Graph has negative edges" );

            if( w.dist > v.dist + cvw )
            {
                w.dist = v.dist +cvw;
                w.prev = v;
                pq.add( new Path( w, w.dist ) );
            }
        }
    }
}

所以我想用较少的加权路径打印未加权的路径,请帮忙。

1 个答案:

答案 0 :(得分:1)

好的,我要粗略地捅这个...循环你的未加权路径列表。对于每个,导航路径结构,累加所有权重。抓住价值最小的那个。您的代码看起来像这样,使用典型的查找最大/最小模式:

int minimum = 99999;  // use a value obviously larger than all paths
PathClass minPath = null;

for (PathClass path : unweightedPaths) {
    int total = 0;

    for (PathItemClass item : path) {
        total += item.weight;
    }

    if (total < minimum) {
        minimum = total;
        minPath = path;
    }
}

// do something with path, which is the smallest weighted path

如果我在正确的轨道上,请告诉我吗?