简体   繁体   中英

Traverse a graph, one vertex, all possible round trips

I have an interesting question at hand. I want to solve a problem of starting from a source vertex of a weighted graph, and find out all possible paths that lead back to it.

For eg: Consider a directed graph above: 在此处输入图片说明


Expected Output If I start from Source=A:

1) A -> C -> D -> B-> A

2) A -> B -> A

3) A -> D -> B -> A

Note:


a) The graph will be weighted and I'am finding the sum(not necessarily minimum sum) of the edges as I traverse.

b) Planning to represent the graph using a matrix, and the graph may be Cyclic at some places.

b) Which is the most efficient code that'll solve this? I know about BFS and DFS, but they dont calculate round trips!

Current DFS CODE: (adjacency graph)

void dfs(int cost[][20],int v[],int n, int j)
{
int i;
v[j]=1;
printf("Vistiing %d\n",j);
for(i=0;i<n;i++)
if(cost[j][i]==1 && v[i]==0)
dfs(cost,v,n,i
);
}

This can be solved by modifying DFS (or BFS).

Consider DFS.

Once you visit the nodes mark it as visited. Once you return from it, mark it un-visited so that other paths can be recognized.

Your example:

Start from A.
Choose a path.
A->B->A.
Return to B. No other paths.
Return to A. Mark B unvisited. Choose another path.
A->D->B->A.
Return to B. No other paths.
Return to D. Mark B unvisited. No other paths.
Return to A. Mark D unvisited. Choose another path.
A->C->D->B->A.

Note: The important thing here is to mark the nodes un-visited.

This sounds like a nice application case for Backtracking :

  • Start with the desired node
  • If you reached the start node for the second time, return the result
  • Otherwise: For each neighbor
    • Add the neighbor to the current path
    • Do the recursion
    • Remove the neighbor from the current path

This is implemented here as an example. Of course, this (particularly the graph data structure) is only a quick sketch to show that the idea is feasible, in a MCVE :

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;


public class GraphRoundTrips
{
    static class Vertex
    {
        String name;
        Vertex(String name)
        {
            this.name = name;
        }
        @Override
        public String toString()
        {
            return name;
        }
    }

    static class Edge
    {
        Vertex v0;
        Vertex v1;
        Edge(Vertex v0, Vertex v1)
        {
            this.v0 = v0;
            this.v1 = v1;
        }
        @Override
        public String toString()
        {
            return "("+v0+","+v1+")";
        }
    }

    static class Graph
    {
        List<Vertex> vertices = new ArrayList<Vertex>();
        List<Edge> edges = new ArrayList<Edge>();

        void addVertex(Vertex v)
        {
            vertices.add(v);
        }
        void addEdge(Edge e)
        {
            edges.add(e);
        }

        List<Vertex> getOutNeighbors(Vertex v)
        {
            List<Vertex> result = new ArrayList<Vertex>();
            for (Edge e : edges)
            {
                if (e.v0.equals(v))
                {
                    result.add(e.v1);
                }
            }
            return result;
        }
    }

    public static void main(String[] args)
    {
        Vertex A = new Vertex("A");
        Vertex B = new Vertex("B");
        Vertex C = new Vertex("C");
        Vertex D = new Vertex("D");

        Graph graph = new Graph();
        graph.addVertex(A);
        graph.addVertex(B);
        graph.addVertex(C);
        graph.addVertex(D);

        graph.addEdge(new Edge(A,C));
        graph.addEdge(new Edge(A,D));
        graph.addEdge(new Edge(A,B));
        graph.addEdge(new Edge(B,A));
        graph.addEdge(new Edge(C,D));
        graph.addEdge(new Edge(D,B));

        compute(graph, A, null, new LinkedHashSet<Vertex>());

    }

    private static void compute(Graph g, Vertex startVertex, 
        Vertex currentVertex, Set<Vertex> currentPath)
    {
        if (startVertex.equals(currentVertex))
        {
            List<Vertex> path = new ArrayList<Vertex>();
            path.add(startVertex);
            path.addAll(currentPath);
            System.out.println("Result "+path);
        }
        if (currentVertex == null)
        {
            currentVertex = startVertex;
        }
        List<Vertex> neighbors = g.getOutNeighbors(currentVertex);
        for (Vertex neighbor : neighbors)
        {
            if (!currentPath.contains(neighbor))
            {
                currentPath.add(neighbor);
                compute(g, startVertex, neighbor, currentPath);
                currentPath.remove(neighbor);
            }
        }
    }



}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM