基本的な深さ優先検索を使用して最小値を見つけることができます。
これはメインのグラフの例です。
ジャバで…
public class Graph {
class Edge{
int w;
int v;
int value;
Edge(int v,int w,int value){
this.v=v;
this.w=w;
this.value=value;
}
}
Graph(int V) {
this.V = V;
this.E = 0;
adj = (List<Integer>[]) new List[V];
paths=new ArrayList<>();
edges=new ArrayList<>();
visited = new boolean[V];
edgeTo = new int[V];
for (int v = 0; v < V; v++) {
adj[v] = new LinkedList<>();
}
}
List<Integer>[] adj;
ArrayList<String> paths;
ArrayList<Edge> edges;
int V;
int E;
int pathTo;
boolean[] visited;
int[] edgeTo;
void addEdge(int v, int w, int value) {
adj[v].add(w);
adj[w].add(v);
edges.add(new Edge(v,w,value));
E++;
}
Edge getEdge(int v, int w){
for(Edge e: edges){
if(e.v==v && e.w==w || e.v==w && e.w==v) return e;
}
return new Edge(-1,-1,0);//randomly chose these values
}
void dfs(Graph G, int s) {
visited = new boolean[G.V];
S(G, s, "");
}
void S(Graph G, int v, String path) {
visited[v] = true;
path+=Integer.toString(v);
if(v == pathTo) paths.add(path);
for (int w : G.adj[v]) {
if (!visited[w]) {
edgeTo[w] = v;
S(G, w, path);
}
}
visited[v] = false;
}
int pathValue(String path){
int result = 0;
for(int i=0;i<path.length()-1;i++){
result+=getEdge(Character.getNumericValue(path.charAt(i)),
Character.getNumericValue(path.charAt(i+1))).value;
}
return result;
}
/**
*
* @param from = starting vertex
* @param to = end vertex
* @return value for the lowest cost path starting at s
*/
int minPath(Graph g, int from,int to){
pathTo = to;
dfs(g,from);
int min=Integer.MAX_VALUE;
for(String path:g.paths){
int val = g.pathValue(path);
if(val<min) min=val;
}
return min;
}
public static void main(String[] args) {
Graph g = new Graph(6);
g.addEdge(0,1,-1);
g.addEdge(1,2,7);
g.addEdge(1,3,6);
g.addEdge(0,5,3);
g.addEdge(5,3,4);
g.addEdge(2,3,5);
g.addEdge(4,2,8);
g.addEdge(4,0,2);
System.out.println(g.minPath(g,0,3));
}
}