OP says: You always travel from first to last vertex. So:
for any i->j, the index j must be greater than i.
And as the example (and according to the OP's explaination), the cost of edges is linear additive. It mean that:
mat[i][k] + mat[k][j] = mat[i][j]
So:
C(i->j) == C
if and only ifmat[i][j] == C.
Assuming there exists mat[i][j] == C
and j-i<=K
, the problem could be simplified to select K-1
nodes from i+1
to j-1
, and list all the combinations. You could simply do this by Algorithm to return all combinations of k elements from n.
Here I wrote a code to solve your example in python for test:
N = 9
mat = [None] * (N-1)
mat [0] =[None, 8, 12, 15, 20, 26, 28, 37, 48]
mat [1] =[None, None, 4, 7, 12, 18, 20, 29, 40]
mat [2] =[None, None, None, 3, 8, 14, 16, 25, 36]
mat [3] =[None, None, None, None, 5, 11, 13, 22, 33]
mat [4] =[None, None, None, None, None, 6, 8, 17, 28]
mat [5] =[None, None, None, None, None, None, 2, 11, 22]
mat [6] =[None, None, None, None, None, None, None, 9, 20]
mat [7] =[None, None, None, None, None, None, None, None, 11]
def xcombination(seq,length):
if not length:
yield []
else
for i in xrange(len(seq)):
for result in xcombination(seq[i+1:],length-1):
yield [seq[i]]+result
def find_path(C, K):
i_j = []
paths = []
for i in range(N):
for j in range(i+1, N):
if mat[i][j] == C:
i_j.append([i, j])
for p in i_j:
if p[1]-p[0] >= K:
paths += [[p[0]]+i+[p[1]] for i in xcombination(range(p[0]+1, p[1]), K-1)]
return paths
paths = find_path(48, 3)
for path in paths:
for step in range(len(path)-1):
print str(path[step])+"->"+str(path[step+1])+"("+str(mat[path[step]][path[step+1]])+") ",
print
The output answer to your example:
0->1(8) 1->2(4) 2->8(36)
0->1(8) 1->3(7) 3->8(33)
0->1(8) 1->4(12) 4->8(28)
0->1(8) 1->5(18) 5->8(22)
0->1(8) 1->6(20) 6->8(20)
0->1(8) 1->7(29) 7->8(11)
0->2(12) 2->3(3) 3->8(33)
0->2(12) 2->4(8) 4->8(28)
0->2(12) 2->5(14) 5->8(22)
0->2(12) 2->6(16) 6->8(20)
0->2(12) 2->7(25) 7->8(11)
0->3(15) 3->4(5) 4->8(28)
0->3(15) 3->5(11) 5->8(22)
0->3(15) 3->6(13) 6->8(20)
0->3(15) 3->7(22) 7->8(11)
0->4(20) 4->5(6) 5->8(22)
0->4(20) 4->6(8) 6->8(20)
0->4(20) 4->7(17) 7->8(11)
0->5(26) 5->6(2) 6->8(20)
0->5(26) 5->7(11) 7->8(11)
0->6(28) 6->7(9) 7->8(11)