我需要编写一个程序,该程序接受整数的方阵并输出最大的子方阵和。输入的第一行是一个整数,它表示方矩阵的尺寸,然后是逐行的实际矩阵。
我有一个正在运行的程序,它输出矩形的最大和而不是所需的正方形。
示例输入:
3
1 2 3
4 5 6
-7 -8 -9
输出:应该是16(2 + 3 + 5 + 6),但是输出21(1 + 2 + 3 + 4 + 5 + 6)
这是我的代码:
#include<iostream>
using namespace std;
int kadaneAlgo(int arr[], int& start, int& end, int n)
{
//find max sum and starting and ending location
int sum = 0, maxSum = INT_MIN;
end = -1; //at first no place is selected
int tempStart = 0; //starting from 0
for (int i = 0; i < n; i++) {
sum += arr[i];
if (sum < 0) {
sum = 0;
tempStart = i + 1;
}
else if (sum > maxSum)
{
//get maximum sum, and update start and end index
maxSum = sum;
start = tempStart;
end = i;
}
}
if (end != -1)
return maxSum;
//when all elements are negative in the array
maxSum = arr[0];
start = end = 0;
// Find the maximum element in array
for (int i = 1; i < n; i++) {
if (arr[i] > maxSum) {
maxSum = arr[i];
start = end = i;
}
}
return maxSum;
}
void maxSqSum()
{
int maxSum = INT_MIN;
int n;
cin >> n;
int left, right;
int temp[n], sum, start, end;
int mat[100][100];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> mat[i][j];
}
}
for (left = 0; left < n; left++) {
for (int i = 0; i < n; i++)//temp initially holds all 0
temp[i] = 0;
for (right = left; right < n; ++right)
{
//for each row, find the sum
for (int i = 0; i < n; ++i)
temp[i] += mat[i][right];
sum = kadaneAlgo(temp, start, end, n);
//find sum of square
if (sum > maxSum) {
//find maximum value of sum, then update corner points
maxSum = sum;
}
}
}
cout << maxSum;
}
int main()
{
maxSqSum();
}