C++程序通过旋转所有行或所有列来最大化矩阵的对角线之和
给定一个维度为N * N的方阵mat[][] ,任务是通过将矩阵的所有行或所有列旋转一个正整数来从给定矩阵中找到可能的对角线元素的最大总和。
例子:
Input: mat[][] = { { 1, 1, 2 }, { 2, 1, 2 }, { 1, 2, 2 } }
Output: 6
Explanation:
Rotating all the columns of matrix by 1 modifies mat[][] to { {2, 1, 2}, {1, 2, 2}, {1, 1, 2} }.
Therefore, the sum of diagonal elements of the matrix = 2 + 2 + 2 = 6 which is the maximum possible.
Input: A[][] = { { -1, 2 }, { -1, 3 } }
Output: 2
方法:想法是用所有可能的方式旋转矩阵的所有行和列,并计算得到的最大和。请按照以下步骤解决问题:
- 初始化一个变量,比如maxDiagonalSum ,通过旋转矩阵的所有行或列来存储矩阵的对角元素的最大可能总和。
- 将矩阵的所有行旋转[0, N – 1]范围内的正整数并更新maxDiagonalSum的值。
- 将矩阵的所有列旋转[0, N – 1]范围内的正整数并更新maxDiagonalSum的值。
- 最后,打印maxDiagonalSum的值。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
#define N 3
// Function to find maximum sum of diagonal elements
// of matrix by rotating either rows or columns
int findMaximumDiagonalSumOMatrixf(int A[][N])
{
// Stores maximum diagonal sum of elements
// of matrix by rotating rows or columns
int maxDiagonalSum = INT_MIN;
// Rotate all the columns by an integer
// in the range [0, N - 1]
for (int i = 0; i < N; i++) {
// Stores sum of diagonal elements
// of the matrix
int curr = 0;
// Calculate sum of diagonal
// elements of the matrix
for (int j = 0; j < N; j++) {
// Update curr
curr += A[j][(i + j) % N];
}
// Update maxDiagonalSum
maxDiagonalSum = max(maxDiagonalSum,
curr);
}
// Rotate all the rows by an integer
// in the range [0, N - 1]
for (int i = 0; i < N; i++) {
// Stores sum of diagonal elements
// of the matrix
int curr = 0;
// Calculate sum of diagonal
// elements of the matrix
for (int j = 0; j < N; j++) {
// Update curr
curr += A[(i + j) % N][j];
}
// Update maxDiagonalSum
maxDiagonalSum = max(maxDiagonalSum,
curr);
}
return maxDiagonalSum;
}
// Driver code
int main()
{
int mat[N][N] = { { 1, 1, 2 },
{ 2, 1, 2 },
{ 1, 2, 2 } };
cout<< findMaximumDiagonalSumOMatrixf(mat);
return 0;
}
输出:
6
时间复杂度: O(N 2 )
辅助空间: O(1)
有关详细信息,请参阅有关通过旋转所有行或所有列来最大化矩阵的对角线总和的完整文章!