ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 矩阵的中心元素等于对角线的一半 > 原文: [https://www.geeksforgeeks.org/center-element-of-matrix-equals-sums-of-half-diagonals/](https://www.geeksforgeeks.org/center-element-of-matrix-equals-sums-of-half-diagonals/) 给定一个奇数阶矩阵,即(5 * 5)。 任务是检查矩阵的中心元素是否等于所有半对角线的总和。 ![](https://img.kancloud.cn/51/58/5158def8bbae2fbfd0ef5f0d6423f1de_300x162.png) **示例**: ``` Input : mat[][] = { 2 9 1 4 -2 6 7 2 11 4 4 2 9 2 4 1 9 2 4 4 0 2 4 2 5 } Output :Yes Explanation : Sum of Half Diagonal 1 = 2 + 7 = 9 Sum of Half Diagonal 2 = 9 + 0 = 9 Sum of Half Diagonal 3 = 11 + -2 = 9 Sum of Half Diagonal 4 = 5 + 4 = 9 Here, All the sums equal to the center element that is mat[2][2] = 9 ``` **简单方法**: 迭代两个循环,找到所有对角线总和,然后检查所有总和是否等于矩阵的中心元素。 如果其中任何一个不等于中心元素,则打印“否”,否则打印“是”。 时间复杂度:O(N * N) **有效方法**:基于[有效方法来找到`O(n)`](https://www.geeksforgeeks.org/efficiently-compute-sums-of-diagonals-of-a-matrix/)中的对角线总和。 以下是此方法的实现 ## C++ ```cpp // C++ Program to check if the center // element is equal to the individual  // sum of all the half diagonals #include <stdio.h> #include<bits/stdc++.h> using namespace std; const int MAX = 100; // Function to Check center element  // is equal to the individual  // sum of all the half diagonals bool HalfDiagonalSums(int mat[][MAX], int n) {         // Find sums of half diagonals     int diag1_left = 0, diag1_right = 0;     int diag2_left = 0, diag2_right = 0;         for (int i = 0, j = n - 1; i < n; i++, j--) {         if (i < n/2) {             diag1_left += mat[i][i];             diag2_left += mat[j][i];                    }         else if (i > n/2) {             diag1_right += mat[i][i];             diag2_right += mat[j][i];                    }     }     return (diag1_left == diag2_right &&              diag2_right == diag2_left &&             diag1_right == diag2_left &&             diag2_right == mat[n/2][n/2]); } // Driver code int main() {     int a[][MAX] = { { 2, 9, 1, 4, -2},                      { 6, 7, 2, 11, 4},                       { 4, 2, 9, 2, 4},                      { 1, 9, 2, 4, 4},                      { 0, 2, 4, 2, 5} };         cout << ( HalfDiagonalSums(a, 5) ? "Yes" : "No" );     return 0; } ```