Cookie Monster - Java Pt. 2

Chris Chen
import java.io.*;
import java.util.*;

public class CookieMonster{

private final int MAX_RC; //maximum rows and columns
private int [][] board; //board of cookies

//default constructor, reads in text file, initializes board
public CookieMonster (String fname, int mrc){

MAX_RC = mrc;
board = new int[MAX_RC][MAX_RC];

Scanner sc = null;

//reads in file
try{

sc = new Scanner(new File (fname));

}catch(FileNotFoundException e){

System.out.println("File not found.");
System.exit(-1);

}//end try catch

//fills the board
for(int i = 0; i < MAX_RC; i++)
for(int j = 0; j < MAX_RC; j++)
board[i][j] = sc.nextInt();

}//end constructor

//moves cookie monster to the end of the board, returns total number of cookies eaten from the most efficient path
public int moveToEnd(int r, int c){

boolean right = canMoveRight(r , c), down = canMoveDown(r , c); //stores the boolean results to save wasteful method calls
int rightSum = Integer.MIN_VALUE, downSum = Integer.MIN_VALUE; //stores the sums of the two diverging paths

//checks if the cookie monster is at a dead end
if(!right && !down){

//checks if the cookie monster is at the end of the path
if(isAtEnd(r , c))
return(board[r][c]);

return(Integer.MIN_VALUE);

}//end if

//checks if the cookie monster can go right
if(right)
rightSum = moveToEnd(r , c + 1);

//checks if the cookie monster can go down
if(down)
downSum = moveToEnd(r + 1 , c);

return(board[r][c] + Math.max(rightSum, downSum) );

}//end moveToEnd

//determines if the object can move down
private boolean canMoveDown(int r, int c){

return (r + 1 < MAX_RC && board[r + 1][c] != -1);

}//end canMoveDown

//determines if the object can move right
private boolean canMoveRight(int r, int c){

return (c + 1 < MAX_RC && board[r][c + 1] != -1);

}//end canMoveRight

//determines if the object is at the end of the board
private boolean isAtEnd(int r, int c){

return (r == MAX_RC-1 && c == MAX_RC-1);

}//end isAtEnd

}//end CookieMonster class

You will need two additional text files with this so you will need to message me if you want them.

Published by Chris Chen

Chris is currently attending the University of California, Berkeley seeking an undergraduate's degree in Electrical Engineering Computer Science. He enjoys playing basketball, practicing kendo, hanging out w...  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.