MAX APPLES THAT CAN BE COLLECTED IN 2D MATRIX
namespace ApplesInTableProblem
{
/*A table composed of N*M cells,each having a certain quantity of apples, is given.
* you start from the upper-left corner.
* At each step you can go down or right one cell.Design an algorithm to find
* the maximum number of apples you can collect ,
* if you are moving from upper-left corner to bottom-right corner.
*/
class Program
{
static void Main(string[] args)
{
int[,] AppleTable = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
for (int i = 0; i < AppleTable.GetLength(0); i++)
{
for (int j = 0; j < AppleTable.GetLength(1); j++)
{
if ((i - 1) < 0 && (j - 1) < 0)
{
continue;
}
if ((i - 1) < 0)
{
AppleTable[i, j] += AppleTable[i, j - 1];
continue;
}
if ((j - 1) < 0)
{
AppleTable[i, j] += AppleTable[i - 1, j];
continue;
}
if (AppleTable[i - 1, j] >= AppleTable[i, j - 1])
{
AppleTable[i, j] += AppleTable[i - 1, j];
}
else
{
AppleTable[i, j] += AppleTable[i, j - 1];
}
}
}
for (int i = 0; i < AppleTable.GetLength(0); i++)
{
for (int j = 0; j < AppleTable.GetLength(1); j++)
{
Console.Write(AppleTable[i,j]+ " ");
}
Console.WriteLine();
}
Console.WriteLine("Max Apples that can be Collected are " + AppleTable[AppleTable.GetLength(0) - 1, AppleTable.GetLength(1) - 1]);
}
}
}
No comments:
Post a Comment