using
System;
class
CombinedMinimumPower
{
static
int
TotalPower(
int
i,
int
j1,
int
j2,
int
[,] power,
int
rows,
int
cols,
int
[,,] memo)
{
if
(i == rows - 1)
return
0;
if
(memo[i, j1, j2] != -1)
return
memo[i, j1, j2];
int
mini =
int
.MaxValue;
for
(
int
k = -1; k <= 1; k++)
{
for
(
int
p = -1; p <= 1; p++)
{
int
nextI = i + 1;
int
nextJ1 = j1 + k;
int
nextJ2 = j2 + p;
if
(nextI >= 0 && nextI < rows && nextJ1 >= 0 && nextJ1 < cols && nextJ2 >= 0 && nextJ2 < cols && nextJ1 != nextJ2)
{
int
value = Math.Abs(power[nextI, nextJ1] - power[i, j1]) + Math.Abs(power[nextI, nextJ2] - power[i, j2]);
value += TotalPower(nextI, nextJ1, nextJ2, power, rows, cols, memo);
mini = Math.Min(mini, value);
}
}
}
memo[i, j1, j2] = mini;
return
mini;
}
static
int
[,,] InitializeMemo(
int
rows,
int
cols1,
int
cols2)
{
int
[,,] memo =
new
int
[rows, cols1, cols2];
for
(
int
i = 0; i < rows; i++)
{
for
(
int
j = 0; j < cols1; j++)
{
for
(
int
k = 0; k < cols2; k++)
{
memo[i, j, k] = -1;
}
}
}
return
memo;
}
public
static
void
Main(
string
[] args)
{
int
[,] power = { { 2, 4, 6 }, { 8, 0, 10 }, { 6, 3, 9 } };
int
rows = power.GetLength(0);
int
cols = power.GetLength(1);
int
[,,] memo = InitializeMemo(rows, cols, cols);
Console.WriteLine(
"Combined Minimum Power: "
+ TotalPower(0, 0, cols - 1, power, rows, cols, memo));
}
}