public static Output TraverseMatrixFromBack(Helfer.Matrix <int> mat) { for (int index = mat.Length - 2; index >= 0; index--) { int botEl = mat.GetRow(index) == mat.RowNum - 1 ? int.MaxValue : mat.GetElement(mat.GetRow(index) + 1, mat.GetCol(index)); // If LAST ROW: int.Max ELSE: take bottom element int rightEl = mat.GetCol(index) == mat.ColNum - 1 ? int.MaxValue : mat.GetElement(mat.GetRow(index), mat.GetCol(index) + 1); // If LAST COL: int.Max ELSE: take right element mat.SetElementAtIndex(index, mat.GetElementAtIndex(index) + Math.Min(botEl, rightEl)); // Add smaller accumulated element to current // This means it goes along the path with the smaller sum // The smaller sum accumulates along the path } Helfer.Point[] trace = new Helfer.Point[mat.RowNum + mat.ColNum - 1]; for (int ind = 0, ptTrace = 0; ptTrace < trace.Length;) { trace[ptTrace++] = new Helfer.Point(mat.GetRow(ind), mat.GetCol(ind)); int botEl = mat.GetRow(ind) == mat.RowNum - 1 ? int.MaxValue : mat.GetElement(mat.GetRow(ind) + 1, mat.GetCol(ind)); int rightEl = mat.GetCol(ind) == mat.ColNum - 1 ? int.MaxValue : mat.GetElement(mat.GetRow(ind), mat.GetCol(ind) + 1); if (botEl < rightEl) { ind = mat.EncodePos(mat.GetRow(ind) + 1, mat.GetCol(ind)); } else { ind = mat.EncodePos(mat.GetRow(ind), mat.GetCol(ind) + 1); } } return(new Output(mat.GetElementAtIndex(0), trace, mat.mat)); }
public static int TraverseMatrixFromBack(Helfer.Matrix <int> mat) { for (int index = mat.Length - 2; index >= 0; index--) { int botEl = mat.GetRow(index) == mat.RowNum - 1 ? int.MaxValue : mat.GetElement(mat.GetRow(index) + 1, mat.GetCol(index)); // If LAST ROW: int.Max ELSE: take bottom element int rightEl = mat.GetCol(index) == mat.ColNum - 1 ? int.MaxValue : mat.GetElement(mat.GetRow(index), mat.GetCol(index) + 1); // If LAST COL: int.Max ELSE: take right element mat.SetElementAtIndex(index, mat.GetElementAtIndex(index) + Math.Min(botEl, rightEl)); // Add smaller accumulated element to current // This means it goes along the path with the smaller sum // The smaller sum accumulates along the path } return(mat.GetElementAtIndex(0)); }