Search code examples
algorithmgraphnodesdepth-first-search

Find distance from node to all other nodes in a weighted graph


How can I find and save the distance from specific node to all other nodes in the graph. Note that graph is acyclic.

This is the code I started with. I pass a vertex, visited array, distance matrix between two nodes which is initially set to 0,
and dist which was supposed to track how far current node is from root node that
I gave as a target.
I use DFS and everytime I go to next node I add distance between them to previous
distance and pass it as an argument to next connection if it exists.
Please help me to complete it.

 void DFSUtil(int v,boolean visited[],ArrayList<ArrayList<Integer>> distanceMatrix,int dist,int targ)
    {
        // Mark the current node as visited and print it
        visited[v]=true;
        System.out.print(v+" ");


        // Recur for all the vertices adjacent to this vertex
        Iterator<Integer> i = adj[v].listIterator();

        while (i.hasNext())
        {
            int n = i.next();

            if (!visited[n]){
                /* dist += distanceMatrix.get(v).get(n);
                System.out.println("cur:"+v+" next:"+n+"\ndistMatrix:"+distanceMatrix.get(v).get(n)+"dist:"+dist);

                distanceMatrix.get(targ).set(n,dist);
                distanceMatrix.get(n).set(targ,dist);
                System.out.println(distanceMatrix);
                System.out.println();*/
                DFSUtil(n, visited,distanceMatrix,dist,targ);
            }
        }
        //remove dist from root to this node
    }

Solution

  • I am assuming that you mean a directed acyclic graph. Dijkstra's can be used which runs in O(E + VlogV).