CodeSignal 8. matrixElementsSum

hjseo-dev·2021년 7월 6일
0

Python 문제풀이

목록 보기
3/7

matrixElementsSum 문제

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이 되는 값이 나오면 그 아래 층의 값은 제외하여 더한다.

✏️ 문제풀이
가장 중요한 것은 행렬을 탐색하는 방법을 코드로 구현하는 것이다. 열에서 부터 행을 위 아래로 탐색하는 방법이 가장 적합하다.
행렬을 탐색할때, 먼저 행과 열의 길이를 추출하고 이중 for 문으로 탐색을 진행한다.

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: #0값이 나오면 멈추고 다음 열 탐색
                total+=m[i][j]
            else:
                break
    return total
    
 #입력
 matrix = [[1, 1, 1, 0], 
          [0, 5, 0, 1], 
          [2, 1, 3, 10]]
 
 #출력
 matrixElementsSum(matrix) = 9 
  1 + 1 + 1 + 5 + 1 = 9

0개의 댓글