Question
After becoming famous, the CodeBots decided to move into a new building together. Each of the rooms has a different cost, and some of them are free, but there's a rumour that all the free rooms are haunted! Since the CodeBots are quite superstitious, they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms.
Given matrix
, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0
).
Example
- For
matrix = [[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]
the output should be
matrixElementsSum(matrix) = 9
. There are several haunted rooms, so we'll disregard them as well as any rooms beneath them. 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 be
matrixElementsSum(matrix) = 9
.
Note that the free room in the final column makes the full column unsuitable for bots (not just the room directly beneath it). Thus, the answer is 1 + 1 + 1 + 5 + 1 = 9
.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.array.integer matrix
A 2-dimensional array of integers representing the cost of each room in the building. A value of
0
indicates that the room is haunted.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.
MY_ANSWER
def matrixElementsSum(matrix):
total = 0
for i in range(len(matrix)): ##열의 길이 구하기
for j in range(len(matrix[i])): # 행의 길이 구하기
if matrix[i][j] == 0:
for k in range(i + 1,len(matrix)):
matrix[k][j] = 0
total = sum(sum(x) for x in matrix)
return total
-> 0을 만나게 되면 그 아래의 열을 0으로 만들어준 다음 전체를 더하는 방식
Best_ANSWER
def matrixElementsSum(m):
r = len(m) #행 개수
c = len(m[0]) #열 개수
total=0
for j in range(c):
for i in range(r):
if m[i][j]!=0:
total+=m[i][j]
else:
break
return total
-> 각 열을 위에서 부터 아래로 순회하는 형식, 순회 도중 0을 만나면 해당 열의 순회는 멈추고 다음 열로 넘어간다.