You are on page 1of 3

/*

* Title: hw6_2.cpp
* Abstract: This program collects maximum number of coins on an n x m
board.
* Author: Andrew Bundy
* ID: 8832
* Date: 12/15/2020
*/
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main()
{
// Get size of board from user.
int x = 0;
int y = 0;
cin >> y;
cin >> x;

// Create empty board.


int board[x][y];
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
board[i][j] = 0;

// Get all board values.


for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
cin >> board[i][j];

/************** Collect maximum number of coins. **************/


int blockedVal = 2; // Value that is inaccessible.

// Create array to store path values.


int pathVals[x][y];
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
pathVals[i][j] = 0;

// Find values for the path array.


for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (i == 0 && j == 0) {
if (board[i][j] == blockedVal)
pathVals[i][j] = 0;
else
pathVals[i][j] = board[i][j];
}
else if (i == 0) {
if (board[i][j] == 1)
pathVals[i][j] = pathVals[i][j-1] + 1;
else if (board[i][j] == 0)
pathVals[i][j] = pathVals[i][j-1];
else if (board[i][j] == blockedVal)
pathVals[i][j] = 0;
}
else if (j == 0) {
if (board[i][j] == 1)
pathVals[i][j] = pathVals[i-1][j] + 1;
else if (board[i][j] == 0)
pathVals[i][j] = pathVals[i][j];
else if (board[i][j] == blockedVal)
pathVals[i][j] = 0;
}
else {
if (board[i][j] == 1) {
if (pathVals[i-1][j] > pathVals[i][j-1])
pathVals[i][j] = pathVals[i-1][j] + 1;
else if (pathVals[i-1][j] < pathVals[i][j-1])
pathVals[i][j] = pathVals[i][j-1] + 1;
else
pathVals[i][j] = pathVals[i-1][j] + 1;
}
else if (board[i][j] == 0) {
if (pathVals[i-1][j] > pathVals[i][j-1])
pathVals[i][j] = pathVals[i-1][j];
else if (pathVals[i-1][j] < pathVals[i][j-1])
pathVals[i][j] = pathVals[i][j-1];
else
pathVals[i][j] = pathVals[i-1][j];
}
else if (board[i][j] == blockedVal)
pathVals[i][j] = 0;
}
}
}

// Determine the best path by backtracking.


int a = x - 1;
int b = y - 1;
stack<string> path; // Holds shortest path.
string coord = ""; // To display coordinates.
bool beginningReached = false;
while (!beginningReached) {
// Once coordinates (0, 0) reached, the path is complete.
if (a < 1 && b < 1)
beginningReached = true;
// Store coordinate.
coord = "(" + to_string(b+1) + "," + to_string(a+1) + ")";
path.push(coord);
coord = "";

// Determine next move.


if (a < 1)
b--;
else if (b < 1)
a--;
else if (pathVals[a-1][b] > pathVals[a][b-1])
a--;
else if (pathVals[a-1][b] < pathVals[a][b-1])
b--;
else
b--;
}

// Display max coins collected.


cout << "Max coins:" << pathVals[x-1][y-1] << "\n";

// Display path followed.


cout << "Path:";
cout << path.top();
path.pop();
while (!path.empty()) {
cout << "->" << path.top();
path.pop();
}
cout << "\n";

return 0;
}

You might also like