找出特殊矩陣元素的總和的 C++ 程式碼
假設我們給出了一個 n * n 維度的方陣。矩陣中的以下值稱為特殊元素 -
主對角線上的值。
第二對角線上的值。
在其上方具有精確 (n - 1 / 2) 行並在其下方具有相同行數的行中的值。
在其左側和右側具有精確 (n - 1 / 2) 列的列中的值。
我們在矩陣中找出這些特殊值之和。
因此,如果輸入如下 n = 4,mat = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}},則輸出將為 107。
步驟
為了解決這個問題,我們將遵循以下步驟 -
res := 0 for initialize i := 0, when i < n, update (increase i by 1), do: for initialize j := 0, when j < n, update (increase j by 1), do: if i is same as j or i is same as n / 2 or j is same as n/ 2 or i + j is same as n - 1, then: res := res + mat[i, j] print(res)
示例
讓我們看看以下實現以獲得更好的理解
#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int n, vector<vector<int>> mat) {
int res = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++){
if (i == j || i == n / 2 || j == n / 2 || i + j == n - 1)
res += mat[i][j];
}
cout << res << endl;
}
int main() {
int n = 4;
vector<vector<int>> mat = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
solve(n, mat);
return 0;
}輸入
4, {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}輸出
107
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP