🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 每个元素是其行号和列号的绝对差的矩阵总和 > 原文: [https://www.geeksforgeeks.org/sum-matrix-element-absolute-difference-row-column-numbers/](https://www.geeksforgeeks.org/sum-matrix-element-absolute-difference-row-column-numbers/) 给定正整数 **n** 。 考虑一个 **n** 行和 **n** 列的矩阵,其中每个元素包含其行号和数字的绝对差。 任务是计算矩阵中每个元素的和。 **示例**: ``` Input : n = 2 Output : 2 Matrix formed with n = 2 with given constraint: 0 1 1 0 Sum of matrix = 2. Input : n = 3 Output : 8 Matrix formed with n = 3 with given constraint: 0 1 2 1 0 1 2 1 0 Sum of matrix = 8. ``` **方法 1(暴力)**: 只需构造一个 n 行 n 列的矩阵,并以其对应的行号和列号的绝对差初始化每个单元格。 现在,找到每个单元格的总和。 以下是上述想法的实现: ## C++ ```cpp // C++ program to find sum of matrix in which each // element is absolute difference of its corresponding // row and column number row. #include<bits/stdc++.h> using namespace std; // Retuen the sum of matrix in which each element // is absolute difference of its corresponding row // and column number row int findSum(int n) {     // Generate matrix     int arr[n][n];     for (int i = 0; i < n; i++)         for (int j = 0; j < n; j++)             arr[i][j] = abs(i - j);     // Compute sum     int sum = 0;     for (int i = 0; i < n; i++)         for (int j = 0; j < n; j++)             sum += arr[i][j];     return sum; } // Driven Program int main() {     int n = 3;     cout << findSum(n) << endl;     return 0; } ```