cst370 HW 6 Example

You might also like

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

/*

* INSTRUCTION:
* This is a Java starting code for hw6_1.
* When you finish the development, download this file.
* Note that the current filename is "Main.java".
* But rename it to "Main_hw6_1.java".
* After that, upload the renamed file on Canvas.
*/

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


/*
* Title: Main_hw6_1.java
* Abstract: This program takes data of a grid from the user and performs
* the maximum coin problem.
* Name: Christopher McMichael
* Date: 10/16/2023
*/

import java.util.*;

class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

int rows = scan.nextInt();


int cols = scan.nextInt();

int[][] grid = new int[rows][cols];

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
grid[i][j] = scan.nextInt();
}
}

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
int left = (j == 0) ? 0 : grid[i][j - 1];
int up = (i == 0) ? 0 : grid[i - 1][j];
int max = (left > up) ? left : up;

grid[i][j] += max;
}
}

ArrayList<String> path = new ArrayList<>();


int currRow = rows - 1;
int currCol = cols - 1;
while (currRow != 0 || currCol != 0) {
path.add("(" + (currRow + 1) + "," + (currCol + 1) + ")");
if (currRow == 0) {
currCol--;
} else if (currCol == 0) {
currRow--;
} else if (grid[currRow][currCol - 1] >= grid[currRow - 1][currCol])
{
currCol--;
} else {
currRow--;
}
}
path.add("(" + 1 + "," + 1 + ")");

System.out.println("Max coins:" + grid[rows - 1][cols - 1]);


System.out.print("Path:");
for (int i = path.size() - 1; i >= 0; i--) {
System.out.print(path.get(i));
if (i != 0) {
System.out.print("->");
} else {
System.out.println("");
}
}
}
}

You might also like