public static int GetMinPathSum3Ways(int[,] a, int rows, int cols) { var memo = new PathVal[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { memo[i, j] = new PathVal(); } } for (int i = 0; i < rows; i++) { memo[i, cols - 1].leftsum = a[i, cols - 1]; } int min = Int32.MaxValue; for (int i = 0; i < rows; i++) { int temp = GetMinPathSum3Ways(a, ref memo, i, 0, rows, cols,constraint.left); min = (min < temp) ? min : temp; } return min; }
public static int GetMinPathSum3Ways(int[,] a, ref PathVal[,] memo, int rpos, int cpos, int rows, int cols, constraint prevdir) { if (rpos >= rows || cpos >= cols) return 0; if (cpos == cols - 1) return memo[rpos, cpos].leftsum; List<int> sums = new List<int>(); if(prevdir==constraint.left) { if (memo[rpos, cpos].leftsum != 0 && memo[rpos, cpos].upsum != 0 && memo[rpos, cpos].downsum != 0) { sums.Add(memo[rpos, cpos].leftsum); sums.Add(memo[rpos, cpos].upsum); sums.Add(memo[rpos, cpos].downsum); return sums.Min(); } } if (prevdir == constraint.up) { if (memo[rpos, cpos].upsum != 0 && memo[rpos, cpos].leftsum != 0) { sums.Add(memo[rpos, cpos].leftsum); sums.Add(memo[rpos, cpos].upsum); return sums.Min(); } } if (prevdir == constraint.down) { if (memo[rpos, cpos].downsum != 0 && memo[rpos, cpos].leftsum != 0) { sums.Add(memo[rpos, cpos].leftsum); sums.Add(memo[rpos, cpos].downsum); return sums.Min(); } } bool right = true, down = true, up = true; if (prevdir == constraint.up) up = false; if (prevdir == constraint.down) down = false; if (cpos + 1 >= cols) right = false; if (rpos + 1 >= rows) down = false; if (rpos - 1 < 0) up = false; if (!right && !down && !up) return 0; int temp1 = Int32.MaxValue, temp2 = Int32.MaxValue, temp3 = Int32.MaxValue; if (right) { temp1 = GetMinPathSum3Ways(a, ref memo, rpos, cpos + 1, rows, cols,constraint.left); memo[rpos, cpos + 1].leftsum = temp1; } if (down) { temp2 = GetMinPathSum3Ways(a, ref memo, rpos + 1, cpos, rows, cols,constraint.up); memo[rpos+1, cpos].upsum = temp2; } if (up) { temp3 = GetMinPathSum3Ways(a, ref memo, rpos - 1, cpos, rows, cols,constraint.down); memo[rpos-1, cpos].downsum = temp3; } memo[rpos, cpos].leftsum = a[rpos,cpos] + Math.Min(Math.Min(temp1, temp2), temp3); return memo[rpos, cpos].leftsum; }