-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrixElementsSum.java
41 lines (32 loc) · 1.18 KB
/
MatrixElementsSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
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.
*/
int matrixElementsSum(int[][] m) {
int total=0;
for(int i=0;i<m[0].length;i++){
total=total+m[0][i];
}
for(int i=1;i<m.length;i++){
for(int j=0;j<m[i].length;j++){
if(m[i-1][j]!=0){
total=total+m[i][j];
}else{
m[i][j]=0;
}
}
}
return total;
}