public Dag(string inputFile) { string[] lines = System.IO.File.ReadAllLines(inputFile); this.size = lines.Length; entryMatrix = new int[size][]; for (int i = 0; i < size; i++) { entryMatrix[i] = new int[size]; string[] values = lines[i].Split(' '); for (int j = 0; j < values.Length; j++) { entryMatrix[i][j] = Int32.Parse(values[j].Trim()); } } maxSumUntilNode = new PathSum[size][]; for (int i = 0; i < size; i++) { maxSumUntilNode[i] = new PathSum[size]; for (int j = 0; j < size; j++) { maxSumUntilNode[i][j] = null; } } }
static void Main(string[] args) { Dag triangle = new Dag("inputs/input2.txt"); PathSum maxSum = triangle.getMaxSum(); Console.WriteLine(maxSum.PrettyString); }
private PathSum getMaxSumUntilNode(int i, int j) { if (i < 0 || j < 0) { return(null); } if (i == 0) { if (j == 0) { if (maxSumUntilNode[0][0] == null) { maxSumUntilNode[0][0] = new PathSum(entryMatrix[0][0]); } return(maxSumUntilNode[0][0]); } return(null); } if (maxSumUntilNode[i][j] != null) { return(maxSumUntilNode[i][j]); } if (CanBeUsedInSum(i, j)) { PathSum max = null; int maxVal = Int32.MinValue; PathSum maxUntilParent1 = getMaxSumUntilNode(i - 1, j); PathSum maxUntilParent2 = getMaxSumUntilNode(i - 1, j - 1); if (maxUntilParent1 != null && maxUntilParent1.Sum > maxVal) { max = maxUntilParent1.Clone(); maxVal = max.Sum; } if (maxUntilParent2 != null && maxUntilParent2.Sum > maxVal) { max = maxUntilParent2.Clone(); maxVal = max.Sum; } if (max != null) { max.addValue(entryMatrix[i][j]); } return(max); } else { return(null); } }
public PathSum Clone() { PathSum result = null; if (path.Count <= 0) { return(result); } result = new PathSum(path[0]); for (int i = 1; i < path.Count; i++) { result.addValue(path[i]); } return(result); }
public PathSum getMaxSum() { PathSum max = null; int maxSum = Int32.MinValue; for (int j = 0; j < size; j++) { PathSum currentLeafMax = getMaxSumUntilNode(size - 1, j); if (currentLeafMax != null && currentLeafMax.Sum > maxSum) { max = currentLeafMax; maxSum = max.Sum; } } return(max); }