Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

#include <iostream>

using namespace std;

int main()
{
// initialize variables
int rows;
int cols;
int maxcoin = 0;
int i = 0, j = 0, k = 0, l = 0, m = 0, n = 0, temp1, temp2, nrows, ncols, coin = 0, ncoins = 0, counter = 0;
bool init = true;

// receive table size and initialize arrays and variables


cin >> rows;
cin >> cols;
nrows = rows + 1;
ncols = cols + 1;
int crws[nrows][ncols];
int mvals[rows][cols];
int steps = rows + cols - 1;
int scount = steps - 1;
int pathi[steps];
int pathj[steps];

// loop array to set coins


for (i = 0; i < nrows; i++)
{
for (j = 0; j < ncols; j++)
{
if (i == 0)
{
crws[i][j] = 0;
}
else if(j == 0)
{
crws[i][j] = 0;
}
else
{
cin >> temp1;
crws[i][j] = temp1;
mvals[i - 1][j - 1] = 0;
}
}
}

// create value matrix array


for (i = 0; i < nrows; i++)
{
for (j = 0; j < ncols; j++)
{
coin = crws[i + 1][j + 1];

if (i == 0 && j == 0)
{
mvals[i][j] = coin;
}
else if (i == 0)
{
mvals[i][j] = coin + mvals[i][j - 1];
}
else if (j == 0)
{
mvals[i][j] = coin + mvals[i - 1][j];
}
else if (mvals[i - 1][j] > mvals[i][j - 1])
{
mvals[i][j] = coin + mvals[i - 1][j];
}
else if (mvals[i - 1][j] < mvals[i][j - 1])
{
mvals[i][j] = coin + mvals[i][j - 1];
}
else
{
mvals[i][j] = coin + mvals[i - 1][j];
}
}
}

// initialize pathing variables and maxcoins output


i = rows - 1;
j = cols - 1;
maxcoin = mvals[i][j];
cout << "Max coins:" << maxcoin << endl;

// create pathing array values through matrix


while (init)
{
if (scount == steps - 1)
{
pathi[scount] = i + 1;
pathj[scount] = j + 1;
scount--;
}
else if (i == 0 && j == 0)
{
init = false;
}
else if (i == 0)
{
j--;
pathi[scount] = i + 1;
pathj[scount] = j + 1;
scount--;
}
else if (j == 0)
{
i--;
pathi[scount] = i + 1;
pathj[scount] = j + 1;
scount--;
}
else if (mvals[i - 1][j] > mvals[i][j - 1])
{
i--;
pathi[scount] = i + 1;
pathj[scount] = j + 1;
scount--;
}
else
{
j--;
pathi[scount] = i + 1;
pathj[scount] = j + 1;
scount--;
}
}

// output optimal path


cout << "Path:";
for (i = 0; i < steps; i++)
{
if (i == 0)
{
cout << "(" << pathi[i] << "," << pathj[i] << ")";
}
else
{
cout << "->(" << pathi[i] << "," << pathj[i] << ")";
}
}
cout << endl;

return 0;
}

You might also like