matrix Elements Sum

matrix Elements Sum

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

  • Formatrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]] the output should be
    solution(matrix) = 9.example 1There 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.
  • Formatrix = [[1, 1, 1, 0], [0, 5, 0, 1], [2, 1, 3, 10]] the output should be
    solution(matrix) = 9.example 2Note 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 matrixA 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] integerThe total price of all the rooms that are suitable for the CodeBots to live in.

 

 

def solution(matrix):
    row_count = len(matrix)
    column_count = len(matrix[0])
   
    print(row_count)
    print(column_count)
    total = 0
    # for row in range(row_count):
    #     print(“———————“)
    #     for column in range(column_count):
    #         if matrix[row][column] != 0:
    #             if row == 0:
    #                 total += matrix[row][column]
    #             elif matrix[row – 1][column] != 0:
    #                 total += matrix[row][column]
    #         print(total)
   
    for column in range(column_count):
        for row in range(row_count):
            if matrix[row][column] == 0:
                break
            else:
                total += matrix[row][column]
    return total
                   
No Comments

Post A Comment