zoukankan      html  css  js  c++  java
  • CodeSignal 刷题 —— matrixElementSum

    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 be
    matrixElementsSum(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 be
    matrixElementsSum(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

      • [execution time limit] 4 seconds (py3)

      • [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.

     题目大意:

    当他们成名后,所有的代码机器人都决定搬到新的建筑里住在一起。建筑是用房间的矩形矩阵表示的。矩阵中的每个单元格都包含一个表示房间价格的整数。有些房间是免费的(费用为0),但这可能是因为它们是闹鬼的,所以所有的机器人都害怕它们。这就是为什么任何空闲的房间或者位于同一列的空闲房间下面的任何地方都不适合机器人居住的原因。

    def matrixElementsSum(matrix):
        sum = 0
        for i in range(len(matrix[0])):      # 先处理第一行
            if matrix[0][i] != 0:
                sum += matrix[0][i]
        for i in range(1, len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i-1][j] == 0:    # 同一列中,如果上一行的元素为0,则把此处的元素也置为0
                    matrix[i][j] =0
                sum += matrix[i][j]
                
        return sum
  • 相关阅读:
    SVO深度解析(三)之深度滤波(建图部分)
    SVO深度解析(二)之跟踪部分
    SVO深度解析(一)之简介和评价
    图像三维重建方法综述
    SLAM优化位姿时,误差函数的雅可比矩阵的推导。
    Canny边缘检测原理与C++实现(2)实现部分
    Canny边缘检测原理与C++实现(1)原理部分
    指针的大小是谁决定的
    Ubuntu 16.04配置CUDA 9.0+cudnn 7.0以及解决Nvidia显卡导致黑屏问题
    安装FAB-Map 2.0,Ubtuntu 16.04
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/9749913.html
Copyright © 2011-2022 走看看