最大子矩阵和 submatrix with maximum sum

#include <iostream>

#define ROWS 4
#define COLS 4

int maxSubSeq(int* a, int n)
{
	int maxSum = 0;
	int curSum = 0;

	for(int i = 0; i < n; i++)
	{
		curSum += a[i];
		if(curSum > maxSum)
			maxSum = curSum;

		if(curSum < 0)
			curSum = 0;
	}

	return maxSum;
};


int maxSumMatrix(int mat[ROWS][COLS], int col, int row)
{
	//initial new matrix
	for(int i = 1; i < col; i++)
	{
		for(int j = 0; j < row; j++)
		{
			mat[j][i] += mat[j][i - 1];
		}
	}


	int maxSum = 0;
	for(int i = 0; i < col; i++)
	{
		for(int j = -1; j < i; j++)
		{
			int* a = (int*)malloc(sizeof(int) * row);

			for(int k = 0; k < row; k++)
			{
				if(j == -1)
				{
					a[k] = mat[k][i];
				}
				else
				{
					a[k] = mat[k][i] - mat[k][j];
				}
			}

			int curSum = maxSubSeq(a, row); 
			if(curSum > maxSum)
			{
				maxSum = curSum;
			}

			free(a);
		}
	}

	return maxSum;
};

int main()
{
	int mat[4][4] = {
						{ 0, -2, -7,  0},
						{ 9,  2, -6,  2},
						{-4,  1, -4,  1},
						{-1,  8,  0, -2}
					};
	int res = maxSumMatrix(mat, 4, 4);
	std::cout << res;

	return 0;
}

你可能感兴趣的:(最大子矩阵和 submatrix with maximum sum)