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

/*

* INSTRUCTION:
* This is a C++ starting code for hw6_1.
* When you finish the development, download this file.
* Note that the current filename is "main.cpp".
* But rename it to "main_hw6_1.cpp".
* After that, upload the renamed file on Canvas.
*/

// Finish the head comment with Abstract, Name, and Date.


/*
* Title: main_hw6_1.cpp
* Abstract: collect maximum number of coins on an n x m board
* which was covered in the class.
* Name: Richard Rivera
* Date: 2/17/23
*/

#include <iostream>
#include <vector>
using namespace std;

void coinMatrix(
int row,
int column,
std::vector<std::vector<int>> &board,
int coin,
std::vector<std::pair<int, int>> currPath,
std::vector<std::pair<int, int>> &optPath,
int &maxcoin);

int main() {
// Declare the int values
int columns, rows;

// Input the values and set parameters


std::cin >> rows >> columns;
std::vector<std::vector<int>> board(rows, std::vector<int>(columns));

// Initialize the coins on the board


for (int x = 0; x < rows; x++) {
for (int y = 0; y < columns; y++) {
std::cin >> board[x][y];
}
}

// Initialize variables
std::vector<std::pair<int, int>> currPath;
std::vector<std::pair<int, int>> optPath;
int currCoin = 0;
int maxCoin = -1;

// Finding the optimal path


coinMatrix(0, 0, board, currCoin, currPath, optPath, maxCoin);

// Print the output


std::cout << "Max coins:" << maxCoin << std::endl;
std::cout << "Path:";

for (std::pair<int, int> path : optPath) {


cout << "(" << path.first << "," << path.second << ")";

if (path.first == rows && path.second == columns) {


cout << endl;
} else {
cout << "->";
}
}
return 0;
}

void coinMatrix(
int row,
int column,
std::vector<std::vector<int>> &board,
int coin,
std::vector<std::pair<int, int>> currPath,
std::vector<std::pair<int, int>> &optPath,
int &maxcoin){

// When the border of the board is exceeded, it returns


if (row >= board.size() || column >= board[0].size()) {
return;
}

// Add a current cell to the current parth


currPath.push_back({row + 1, column + 1});
// If the current coins exceed the max coin, update the opt path and max
// coin results
if ((row == board.size() - 1) && (column == board[0].size() - 1)) {
if (coin + board[row][column] > maxcoin) {
maxcoin = coin + board[row][column];
optPath = currPath;
}
return;
}

// Look through the board and add coins for each cell
int currCoin = coin + board[row][column];

coinMatrix(row + 1, column, board, currCoin, currPath, optPath, maxcoin);


coinMatrix(row, column + 1, board, currCoin, currPath, optPath, maxcoin);
}

You might also like