The problem can be solved by dynamic programming as follows. Let the formal determination of his decision begin.
Given DAG G = (V, E) , let C be the set of vertices visited so far, and w[i, j] and c[i] weight (distance) associated with the edge (i, j) , respectively, and color vertex i . Note that w[i, j] is zero if the edge (i, j) does not belong to E Now we define the distance d for the transition from vertex i to vertex j taking C into account as
d[i, j, C] = w[i, j] if i is not equal to j and c[j] does not belong to C = 0 if i = j = infinite if i is not equal to j and c[j] belongs to C
Now we are ready to define our subtasks as follows:
A[i, j, k, C] = the shortest path from i to j that uses exactly k edges and respects the colors in C , so that two vertices in the path are not colored using the same color (one of the colors in C )
Let m be the maximum number of edges allowed in the path, and suppose that the vertices are labeled 1, 2, ..., n . Let P[i,j,k] be the previous vertex j in the shortest path satisfying the restrictions from i to j . The following algorithm solves the problem.
for k = 1 to m for i = 1 to n for j = 1 to n A[i,j,k,C] = min over x belonging to V {d[i,x,C] + A[x,j,k-1,C union c[x]]} P[i,j,k] = the vertex x that minimized A[i,j,k,C] in the previous statement
Set the initial conditions as follows:
A[i,j,k,C] = 0 for k = 0 A[i,j,k,C] = 0 if i is equal to j A[i,j,k,C] = infinite in all of the other cases
The total computational complexity of the O(mn^3) algorithm; taking into account that in your particular case m = 14 (since you want exactly 15 nodes), it follows that m = O(1) , so the complexity is actually O(n^3) . To represent set C use a hash table so that nesting and membership testing requires O (1) on average. Note that in the algorithm, the operation C union c [x] is actually an insert operation in which you add the color of the vertex x to the hash table for C. However, since you insert only one element, the union operation set produces exactly the same result (if the color is not in the set, it is added, otherwise it is simply discarded and the set does not change). Finally, to represent a DAG, use the adjacency matrix.
Once the algorithm is executed to find the minimum shortest path among all possible vertices i and j , just find the minimum among the values of A[i,j,m,C] . Note that if this value is infinite, then there is no valid shortest path. If there is a real shortest path, you can determine it using the values of P[i,j,k] and tracing back through the vertices of the predecessor. For example, starting with a = P[i,j,m] last edge on the shortest path (a,j) , the previous edge is given by b = P[i,a,m-1] , and its value is (b,a) and etc.