This is the problem:
I have n points (p1, p2, p3, .. pn), each of them can connect to any other with a determined cost x.
Each point belongs to one of a set of p
You can use the Floyd–Warshall algorithm. Here's the pseudocode given by WikiPedia:
/* Assume a function edgeCost(i,j) which returns the cost of the edge from i to
(infinity if there is none).
Also assume that n is the number of vertices and edgeCost(i,i)=0
*/
int path[][];
/* A 2-dimensional matrix. At each step in the algorithm, path[i][j] is the shortest path
from i to j using intermediate vertices (1..k-1). Each path[i][j] is initialized to
edgeCost(i,j) or infinity if there is no edge between i and j.
*/
procedure FloydWarshall ()
for k: = 1 to n
for each (i,j) in {1,..,n}2
path[i][j] = min ( path[i][j], path[i][k]+path[k][j] );
I had to write a program for an algorithms course about this same problem. This algorithm worked like a charm! Goodluck.
This is how I presently interpret your problem.
Red arrows are me manually tracing the paths that conform to the given ordering constraint.
Costs are not provided, but it is assumed all links incur a cost, and the link costs are different.
If this accurately describes the scenario you are trying to solve, please say so, so that others can better answer the question.
As Jan mentioned, you just need a normal boring shortest path algorithm (like Dijkstra's or Floyd's algorithm); however, you need to transform your input graph so that the output path will respect your path constraint.
Given a path constraint of: A - B - A
Create a new graph G
and insert all of the vertexes from A
into G
with new labels like a_01. Then insert all the vertexes from B
into G
and connect the A
vertexes with the B
vertexes (edges should be directed towards the newly inserted nodes) copying the costs from the original graph. You then repeat this step with A
(and any other path components) connecting the newly inserted vertexes to those in B
. Thus, you create a graph where only the paths that exist satisfy the path constraint. You can then use normal shortest path algorithms.
The key insight is that when you revisit a class you are actually visiting a distinct set of nodes and that you only want edges that connect adjacent classes of nodes.
Hope this is clear.
This solution is not particularly efficient, but clearly polynomial.
On the revision of your question it seems you ask for one node per letter - in that case it is a simple dynamic programming solution: Calculate all the shortest paths of length 1, which satisfy the beginning of your sequence, between each pair of nodes. Then having for k all such paths for all node pairs, it is trivial to construct for k+1.
As far as I understand your question you need a shortest path in a directed graph. http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm should give you an idea.
regards, Jan