Problem
After they became famous, the CodeBots all decided to move to a new building and live together. The building is represented by a rectangular matrix
of rooms. Each cell in the matrix
contains an integer that represents 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 to live in.
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 bematrixElementsSum(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
.
- For
matrix = [[1, 1, 1, 0],
[0, 5, 0, 1],
[2, 1, 3, 10]]
the output should bematrixElementsSum(matrix) = 9
.
Here's the rooms matrix with unsuitable rooms marked with 'x'
:
[[1, 1, 1, x],
[x, 5, x, x],
[x, 1, x, x]]
Note that the free room in the first row make the full column unsuitable for bots.
Thus, the answer is 1 + 1 + 1 + 5 + 1 = 9
.
Input/Output
[input] array.array.integer matrix
A 2-dimensional array of integers representing a rectangular matrix of the building.
Guaranteed constraints:
1 ≤ matrix.length ≤ 5
,1 ≤ matrix[i].length ≤ 5
,0 ≤ matrix[i][j] ≤ 10
.[output] integer
The total price of all the rooms that are suitable for the CodeBots to live in.
Solution
2차원 배열의 탐색을 위해 중첩 for문을 사용하였습니다.
만약 [i][j]의 값이 0이라면, 그 아래에 위치하는 값을 0으로 바꾸는 방식으로 진행하였습니다.
'Programming > Algorithm' 카테고리의 다른 글
[Algorithm] commonCharacterCount (0) | 2018.02.09 |
---|---|
[Algorithm] allLongestStrings (0) | 2018.02.09 |
[Algorithm] almostIncreasingSequence (0) | 2018.02.08 |
[Algorithm] makeArrayConsecutive2 (0) | 2018.02.08 |
[Algorithm] shapeArea (0) | 2018.02.08 |