public static PyramidBrick CreatePyramid() { #region PYRAMID_CREATION List <PyramidBrick> pyramidRows = new List <PyramidBrick>(); List <PyramidBrick> pyramidRowsInCreation = new List <PyramidBrick>(); for (int i = pyramidInput.Count() - 1; i >= 0; i--) { pyramidRowsInCreation = new List <PyramidBrick>(); for (int j = 0; j < pyramidInput[i].Count(); j++) { PyramidBrick brick = new PyramidBrick(pyramidInput[i][j], null, null); if (pyramidRows.Count() > j) { brick.LeftChild = pyramidRows[j]; brick.RightChild = pyramidRows[j + 1]; } pyramidRowsInCreation.Add(brick); } pyramidRows = pyramidRowsInCreation; } #endregion return(pyramidRows[0]); }
static void Main(string[] args) { Console.WriteLine("Program start."); PyramidBrick root = CreatePyramid(); SearchForTheMaxSumPath(root, root.Value, new List <PyramidBrick>() { root }); Console.WriteLine($"Result: maximum posible sum in this pyramid is {maxSum}."); Console.WriteLine($"The path is {ReturnStringPath()}."); Console.ReadKey(); }
public PyramidBrick(int value, PyramidBrick leftChild, PyramidBrick rightChild) { Value = value; LeftChild = leftChild; RightChild = rightChild; }
public static void SearchForTheMaxSumPath(PyramidBrick brick, int sum, List <PyramidBrick> sumPath) { PyramidBrick child = brick; bool childIsRight = false; #region PATH_SEARCH //path search (left priority) if ((brick.LeftChild.Value + brick.Value) % 2 == 1) { child = brick.LeftChild; } else if ((brick.RightChild.Value + brick.Value) % 2 == 1) { childIsRight = true; child = brick.RightChild; } else { return; } sum = sum + child.Value; sumPath.Add(child); if (child.LeftChild == null && child.RightChild == null) { if (sum > maxSum) { maxSum = sum; maxSumPath = new List <PyramidBrick>(sumPath); } sumPath.Remove(child); return; } #endregion SearchForTheMaxSumPath(child, sum, sumPath); #region SEARCH_FOR_ANOTHER_PATH //returning + searching for yet unexplored path (left -> right) if ((brick.RightChild.Value + brick.Value) % 2 == 1 && !childIsRight) { sum = sum - child.Value + brick.RightChild.Value; sumPath.Remove(child); child = brick.RightChild; sumPath.Add(child); if (child.LeftChild == null && child.RightChild == null) { if (sum > maxSum) { maxSum = sum; maxSumPath = new List <PyramidBrick>(sumPath); } sumPath.Remove(child); return; } SearchForTheMaxSumPath(brick.RightChild, sum, sumPath); //if returned here, there is no need to check for the possible right path - we already explored it } #endregion sumPath.Remove(child); return; }