11
22using Advanced . Algorithms . DataStructures . Graph . AdjacencyList ;
3+ using System ;
34using System . Collections . Generic ;
45using System . Linq ;
56
@@ -9,21 +10,25 @@ namespace Advanced.Algorithms.Graph
910 /// Uses dynamic programming for a
1011 /// psuedo-polynomial time runTime complexity for this NP hard problem.
1112 /// </summary>
12- public class TravellingSalesman
13+ public class TravellingSalesman < T , W > where W : IComparable
1314 {
14- public static int FindMinWeight ( WeightedDiGraph < int , int > graph )
15+ IShortestPathOperators < W > @operator ;
16+
17+ public W FindMinWeight ( WeightedDiGraph < T , W > graph , IShortestPathOperators < W > @operator )
1518 {
19+ this . @operator = @operator ;
20+
1621 return findMinWeight ( graph . ReferenceVertex , graph . ReferenceVertex ,
1722 graph . VerticesCount ,
18- new HashSet < WeightedDiGraphVertex < int , int > > ( ) ,
19- new Dictionary < string , int > ( ) ) ;
23+ new HashSet < WeightedDiGraphVertex < T , W > > ( ) ,
24+ new Dictionary < string , W > ( ) ) ;
2025 }
2126
22- private static int findMinWeight ( WeightedDiGraphVertex < int , int > currentVertex ,
23- WeightedDiGraphVertex < int , int > tgtVertex ,
27+ private W findMinWeight ( WeightedDiGraphVertex < T , W > currentVertex ,
28+ WeightedDiGraphVertex < T , W > tgtVertex ,
2429 int remainingVertexCount ,
25- HashSet < WeightedDiGraphVertex < int , int > > visited ,
26- Dictionary < string , int > cache )
30+ HashSet < WeightedDiGraphVertex < T , W > > visited ,
31+ Dictionary < string , W > cache )
2732 {
2833 var cacheKey = $ "{ currentVertex . Value } -{ remainingVertexCount } ";
2934
@@ -34,7 +39,7 @@ private static int findMinWeight(WeightedDiGraphVertex<int, int> currentVertex,
3439
3540 visited . Add ( currentVertex ) ;
3641
37- var results = new List < int > ( ) ;
42+ var results = new List < W > ( ) ;
3843
3944 foreach ( var vertex in currentVertex . OutEdges )
4045 {
@@ -50,9 +55,9 @@ private static int findMinWeight(WeightedDiGraphVertex<int, int> currentVertex,
5055 {
5156 var result = findMinWeight ( vertex . Key , tgtVertex , remainingVertexCount - 1 , visited , cache ) ;
5257
53- if ( result != int . MaxValue )
58+ if ( ! result . Equals ( @operator . MaxValue ) )
5459 {
55- results . Add ( result + vertex . Value ) ;
60+ results . Add ( @operator . Sum ( result , vertex . Value ) ) ;
5661 }
5762
5863 }
@@ -62,7 +67,7 @@ private static int findMinWeight(WeightedDiGraphVertex<int, int> currentVertex,
6267
6368 if ( results . Count == 0 )
6469 {
65- return int . MaxValue ;
70+ return @operator . MaxValue ;
6671 }
6772
6873 var min = results . Min ( ) ;
0 commit comments