I'm working on Java via the Codefights website. This is the exercise:
After becoming famous, CodeBots decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms, each cell containing an integer - the price of the room. Some rooms are free (their cost is 0), but that's probably because they are haunted, so all the bots are afraid of them. That is why any room that is free or is located anywhere below a free room in the same column is not considered suitable for the bots. Help the bots calculate the total price of all the rooms that are suitable for them. Example: For
matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
the output should be
matrixElementsSum(matrix) = 9
. Here's the rooms matrix with unsuitable rooms marked with 'x':[[x, 1, 1, 2], [x, 5, x, x], [x, x, x, x]]
Thus, the answer is 1 + 5 + 1 + 2 = 9.
I understand that I've got to go through all the elements of the array, which is easy. The part I'm hung up on is checking on the "0" rooms above the current element in the array. I know that that position will be matrix[i-1][j], where the current position in the array is matrix[i][j]. But, I'm getting an error "InvocationTargetExeption" when I try to implement this.
My assumption is that I'm asking for negative numbers in the array address, but I'm not sure how to fix this. Here's my code:
int matrixElementsSum(int[][] matrix) {
int sum = 0;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
if(matrix[i-1][j]==0){ sum += 0;}
else{sum += matrix[i][j];}
}
}
return sum;
}