-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathTravellingSalesman.cs
73 lines (58 loc) · 2.44 KB
/
TravellingSalesman.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Linq;
using Advanced.Algorithms.DataStructures.Graph;
namespace Advanced.Algorithms.Graph;
/// <summary>
/// Uses dynamic programming for a
/// psuedo-polynomial time runTime complexity for this NP hard problem.
/// </summary>
public class TravellingSalesman<T, TW> where TW : IComparable
{
private IShortestPathOperators<TW> @operator;
public TW FindMinWeight(IGraph<T> graph, IShortestPathOperators<TW> @operator)
{
this.@operator = @operator;
if (this.@operator == null)
throw new ArgumentException("Provide an operator implementation for generic type W during initialization.");
if (!graph.IsWeightedGraph)
if ([email protected]() != typeof(int))
throw new ArgumentException("Edges of unweighted graphs are assigned an imaginary weight of one (1)." +
"Provide an appropriate IShortestPathOperators<int> operator implementation during initialization.");
return FindMinWeight(graph.ReferenceVertex, graph.ReferenceVertex,
graph.VerticesCount,
new HashSet<IGraphVertex<T>>(),
new Dictionary<string, TW>());
}
private TW FindMinWeight(IGraphVertex<T> sourceVertex,
IGraphVertex<T> tgtVertex,
int remainingVertexCount,
HashSet<IGraphVertex<T>> visited,
Dictionary<string, TW> cache)
{
var cacheKey = $"{sourceVertex.Key}-{remainingVertexCount}";
if (cache.ContainsKey(cacheKey)) return cache[cacheKey];
visited.Add(sourceVertex);
var results = new List<TW>();
foreach (var edge in sourceVertex.Edges)
{
//base case
if (edge.TargetVertex.Equals(tgtVertex)
&& remainingVertexCount == 1)
{
results.Add(edge.Weight<TW>());
break;
}
if (!visited.Contains(edge.TargetVertex))
{
var result = FindMinWeight(edge.TargetVertex, tgtVertex, remainingVertexCount - 1, visited, cache);
if (!result.Equals(@operator.MaxValue)) results.Add(@operator.Sum(result, edge.Weight<TW>()));
}
}
visited.Remove(sourceVertex);
if (results.Count == 0) return @operator.MaxValue;
var min = results.Min();
cache.Add(cacheKey, min);
return min;
}
}