public string GetAnswer() { long[,] matrix = S81.GetMatrix(); long[,] sums = new long[dim, dim]; for (int i = 0; i < dim; i++) { sums[i, 0] = matrix[i, 0]; } for (int j = 1; j < dim; j++) { // from column j-1 to column j for (int i = 0; i < dim; i++) { // consider row i long min = long.MaxValue; for (int k = 0; k < dim; k++) { long temp = sums[k, j - 1] + matrix[i, j]; int begin; int end; if (k < i) { begin = k + 1; end = i; } else { begin = i; end = k - 1; } for (int index = begin; index <= end; index++) { temp += matrix[index, j - 1]; } if (temp < min) { min = temp; } } sums[i, j] = min; } } var lastColumn = new List <long>(); for (int i = 0; i < dim; i++) { lastColumn.Add(sums[i, dim - 1]); } return(lastColumn.Min().ToString()); }
public string GetAnswer() { long[,] matrix = S81.GetMatrix(); long[,] sum = new long[dim, dim]; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { sum[i, j] = int.MaxValue; } } sum[0, 0] = matrix[0, 0]; var pointsToBeUpdated = new Queue <Tuple <int, int> >(); pointsToBeUpdated.Enqueue(new Tuple <int, int>(0, 0)); while (pointsToBeUpdated.Count != 0) { var point = pointsToBeUpdated.Dequeue(); if (CanMoveToLeft(point)) { long newValue = sum[point.Item1, point.Item2] + matrix[point.Item1 - 1, point.Item2]; if (newValue < sum[point.Item1 - 1, point.Item2]) { sum[point.Item1 - 1, point.Item2] = newValue; pointsToBeUpdated.Enqueue(new Tuple <int, int>(point.Item1 - 1, point.Item2)); } } if (CanMoveToRight(point)) { long newValue = sum[point.Item1, point.Item2] + matrix[point.Item1 + 1, point.Item2]; if (newValue < sum[point.Item1 + 1, point.Item2]) { sum[point.Item1 + 1, point.Item2] = newValue; pointsToBeUpdated.Enqueue(new Tuple <int, int>(point.Item1 + 1, point.Item2)); } } if (CanUp(point)) { long newValue = sum[point.Item1, point.Item2] + matrix[point.Item1, point.Item2 - 1]; if (newValue < sum[point.Item1, point.Item2 - 1]) { sum[point.Item1, point.Item2 - 1] = newValue; pointsToBeUpdated.Enqueue(new Tuple <int, int>(point.Item1, point.Item2 - 1)); } } if (CanDown(point)) { long newValue = sum[point.Item1, point.Item2] + matrix[point.Item1, point.Item2 + 1]; if (newValue < sum[point.Item1, point.Item2 + 1]) { sum[point.Item1, point.Item2 + 1] = newValue; pointsToBeUpdated.Enqueue(new Tuple <int, int>(point.Item1, point.Item2 + 1)); } } } return(sum[dim - 1, dim - 1].ToString()); }