最大子矩阵和的c++代码
时间: 2023-10-30 17:47:26 浏览: 137
C++实现的最大子矩阵和
我可以帮您提供最大子矩阵和的C代码,代码如下:
#include <stdio.h>
#include <limits.h>
#define ROW 4
#define COL 5
int maxSubArraySum(int arr[], int n)
{
int max_so_far = INT_MIN, max_ending_here = 0;
for (int i = 0; i < n; i++)
{
max_ending_here = max_ending_here + arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
int maxSubMatrix(int matrix[][COL])
{
int max_sum = INT_MIN;
int temp[ROW] = {0};
for (int left = 0; left < COL; ++left)
{
for (int i = 0; i < ROW; ++i)
temp[i] = 0;
for (int right = left; right < COL; ++right)
{
for (int i = 0; i < ROW; ++i)
temp[i] += matrix[i][right];
int sum = maxSubArraySum(temp, ROW);
if (sum > max_sum)
max_sum = sum;
}
}
return max_sum;
}
int main()
{
int matrix[ROW][COL] = {
{1, 2, -1, -4, -20},
{-8, -3, 4, 2, 1},
{3, 8, 10, 1, 3},
{-4, -1, 1, 7, -6}
};
printf("Maximum sum of submatrix is %d", maxSubMatrix(matrix));
return 0;
}
阅读全文