当前位置: 面试刷题>> 平面范围求和——不可变矩阵 (经典算法题500道)


题目描述补充

题目:平面范围求和——不可变矩阵

给定一个二维矩阵 matrix(不可变,即不能修改矩阵中的值),和一个目标范围 [row1, col1, row2, col2](其中 (row1, col1) 是范围的左上角坐标,(row2, col2) 是范围的右下角坐标),要求计算该范围内所有元素的和。

注意:

  1. 矩阵中的元素都是非负整数。
  2. 行和列的索引从0开始。
  3. 假设输入的坐标范围总是有效的,即 0 <= row1 <= row2 < matrix.length0 <= col1 <= col2 < matrix[0].length

示例

假设矩阵 matrix 如下:

[
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

给定范围 [1, 1, 2, 2],即计算第1行到第2行(包含)和第1列到第2列(包含)的元素之和,结果为 6 + 3 + 2 + 1 = 12

PHP 示例代码

function sumRegion($matrix, $row1, $col1, $row2, $col2) {
    $sum = 0;
    for ($i = $row1; $i <= $row2; $i++) {
        for ($j = $col1; $j <= $col2; $j++) {
            $sum += $matrix[$i][$j];
        }
    }
    return $sum;
}

// 示例用法
$matrix = [
    [3, 0, 1, 4, 2],
    [5, 6, 3, 2, 1],
    [1, 2, 0, 1, 5],
    [4, 1, 0, 1, 7],
    [1, 0, 3, 0, 5]
];

$result = sumRegion($matrix, 1, 1, 2, 2);
echo "Sum of the region: " . $result; // 输出: Sum of the region: 12

Python 示例代码

def sumRegion(matrix, row1, col1, row2, col2):
    return sum(row[col1:col2+1] for row in matrix[row1:row2+1])

# 示例用法
matrix = [
    [3, 0, 1, 4, 2],
    [5, 6, 3, 2, 1],
    [1, 2, 0, 1, 5],
    [4, 1, 0, 1, 7],
    [1, 0, 3, 0, 5]
]

result = sumRegion(matrix, 1, 1, 2, 2)
print("Sum of the region:", result) # 输出: Sum of the region: 12

JavaScript 示例代码

function sumRegion(matrix, row1, col1, row2, col2) {
    let sum = 0;
    for (let i = row1; i <= row2; i++) {
        for (let j = col1; j <= col2; j++) {
            sum += matrix[i][j];
        }
    }
    return sum;
}

// 示例用法
const matrix = [
    [3, 0, 1, 4, 2],
    [5, 6, 3, 2, 1],
    [1, 2, 0, 1, 5],
    [4, 1, 0, 1, 7],
    [1, 0, 3, 0, 5]
];

const result = sumRegion(matrix, 1, 1, 2, 2);
console.log("Sum of the region:", result); // 输出: Sum of the region: 12

码小课:在算法和数据结构的学习中,掌握不同编程语言的实现方式对于提升编程能力和思维广度至关重要。以上示例展示了如何在PHP、Python和JavaScript中处理二维数组和范围求和的问题,更多相关内容欢迎访问码小课网站进行学习和探讨。

推荐面试题