[codesignal][python] 6. matirxElementsSum
Computer Science/알고리즘 문제풀이

[codesignal][python] 6. matirxElementsSum

codesignal.com

 

Coding Tests and Assessments for Technical Hiring | CodeSignal

Learn how you can go beyond resumes in technical hiring with a state-of-the-art assessment platform and advanced coding tests

codesignal.com

level : easy

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).

0이 있는 공간이 유령이 있는 공간이다. 

오로지 열 기준으로만 내려가다가 유령이 있으면 더 이상 내려가지 않고, 유령이 없고 숫자가 있다면 계속 더해주는 sum을 구하면 된다.

내려가다가 유령이 나타나면 그 아래 숫자는 버리면 된다.

Example: 

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.

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.

 

 

My answer:


def matrixElementsSum(matrix):
    row=len(matrix)
    column=len(matrix[0])
    sum=0
    for i in range(column):
        for j in range(row):
            if (matrix[j][i]==0):
                break
            sum+=matrix[j][i]
    return sum
  • row, column 을 구하고 column기준으로 내려가면서 0이 있는지 탐색한다
  • 0이 있으면  더이상 내려가면서 탐색할 필요가 없기 때문에 break
  • 0이 아닌 숫자라면 계속 더해 나가면 됨