-2

We are provided with an undirected graph, source node, destination node and the weight of an extra edge which you can use to connect any two nodes which were not connected earlier. You have to find the minimum weight of the path possible between the source and the destination. You can use the provided edge only once. Here is an example : a Graph with 5 edges as follows 1->2 the weight is 1,2->3 the weight is 2,3->4 the weight is 3,4->5 the weight is 1,1->4 the weight is 3 and source vertex is vertex 1,destination is vertex 4. We have to tell that the minimum path length. (which is 2 in this case) We can use add an extra edge of weight 1(here from 1 to 5 ) I would like to know how can this be implemented in java.

2 Answers2

0

If I understand the question correctly, then all you're looking for is an implementation of breadth first search in java, that could be found here. and I don't see any use for the extra edge weight (as that would just increase the distance) unless you use the extra edge to create a direct path between 1 and 4. (i.e. the source and destination) so the shortest distance would become 1. But again, you would have to check in each case if this extra edge holds weight lesser than that achieved from breadth first search. Also, without using the extra edge, the shortest distance is 3 in this case, not 2.

0

Let's assume you have no zero and negative edges. You keep edges in array a[N][ N]. Modify graph a bit:

  • make directed graph A out of source graph:

    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            if (a[i][j] > 0 && a[j][i] == 0)
                a[j][i] = a[i][j];
    
  • make a copy of graph and add wild edge (wild edge is directed, leads from part A to part B, has predefined weight)

  • define array b: int b[2*N][2*N], initialize edges with zeroes

    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            if (a[i][j] == 0) {
                b[i][N+j] = wildWeight;
            } else {
                b[i][j] = a[i][j];
                b[N+i][N+j] = a[i][j];
            }   
    

Google for Dijkstra algorithm implementation in java and use it on that midified graph.

Alexander Anikin
  • 1,053
  • 5
  • 14