#include <iostream> #include <vector> #include <climits> using namespace std;
class MaxSubRectangle { public: static int bruteForce(vector<vector<int>>& matrix) { if (matrix.empty() || matrix[0].empty()) return 0; int m = matrix.size(), n = matrix[0].size(); int maxSum = INT_MIN; for (int top = 0; top < m; top++) { for (int left = 0; left < n; left++) { vector<int> colSum(n, 0); for (int bottom = top; bottom < m; bottom++) { for (int right = left; right < n; right++) { colSum[right] += matrix[bottom][right]; int sum = 0; for (int k = left; k <= right; k++) { sum += colSum[k]; } maxSum = max(maxSum, sum); } } } } return maxSum; } static int optimized(vector<vector<int>>& matrix) { if (matrix.empty() || matrix[0].empty()) return 0; int m = matrix.size(), n = matrix[0].size(); int maxSum = INT_MIN; for (int top = 0; top < m; top++) { vector<int> colSum(n, 0); for (int bottom = top; bottom < m; bottom++) { for (int j = 0; j < n; j++) { colSum[j] += matrix[bottom][j]; } int currentSum = 0; for (int j = 0; j < n; j++) { currentSum = max(colSum[j], currentSum + colSum[j]); maxSum = max(maxSum, currentSum); } } } return maxSum; } static vector<int> findMaxSubRectangle(vector<vector<int>>& matrix) { if (matrix.empty() || matrix[0].empty()) return {0, 0, 0, 0, 0}; int m = matrix.size(), n = matrix[0].size(); int maxSum = INT_MIN; vector<int> result(5); for (int top = 0; top < m; top++) { vector<int> colSum(n, 0); for (int bottom = top; bottom < m; bottom++) { for (int j = 0; j < n; j++) { colSum[j] += matrix[bottom][j]; } int currentSum = 0; int start = 0; int maxCurrent = INT_MIN; int tempStart = 0, tempEnd = 0; for (int j = 0; j < n; j++) { if (currentSum <= 0) { currentSum = colSum[j]; tempStart = j; } else { currentSum += colSum[j]; } if (currentSum > maxCurrent) { maxCurrent = currentSum; tempEnd = j; start = tempStart; } } if (maxCurrent > maxSum) { maxSum = maxCurrent; result[0] = top; result[1] = start; result[2] = bottom; result[3] = tempEnd; result[4] = maxSum; } } } return result; } };
int main() { vector<vector<int>> matrix = { {1, 2, -1, -4, -20}, {-8, -3, 4, 2, 1}, {3, 8, 10, 1, 3}, {-4, -1, 1, 7, -6} }; cout << "暴力解法结果: " << MaxSubRectangle::bruteForce(matrix) << endl; cout << "优化解法结果: " << MaxSubRectangle::optimized(matrix) << endl; vector<int> rect = MaxSubRectangle::findMaxSubRectangle(matrix); cout << "最大子矩形位置: (" << rect[0] << ", " << rect[1] << ") 到 (" << rect[2] << ", " << rect[3] << ")" << endl; cout << "最大和: " << rect[4] << endl; return 0; }
|