题目要求:
求一个矩阵中最大的二维矩阵(元素和最大).如:
1 2 0 3 4
2 3 4 5 1
1 1 5 3 0
中最大的是4 5
5 3.
要求:1)写出算法;2)分析时间复杂度;3)写出相关代码。
参考资料:编程之美 2.15
题目分析:
从矩阵开头逐个求2*2矩阵的和,找出最大,时间复杂度O(M*N),M/N为行/列;
代码实现:
#include <iostream> using namespace std; const int M = 3; const int N = 5; int FindMaxMatrix(int a[][N],int &res_i,int &res_j); int main(void) { int res_i,res_j; int a[M][N] = {{1,2,0,3,4},{2,3,4,5,1},{1,2,5,3,0}}; int max = FindMaxMatrix(a,res_i,res_j); cout << "The max matrix is:" << endl << a[res_i][res_j] << " " ; cout << a[res_i][res_j+1] << endl<<a[res_i+1][res_j] << " " << a[res_i+1][res_j+1] << endl; cout << "and the max sum is:" << max << endl; return 0; } int FindMaxMatrix(int a[][N],int &res_i,int &res_j) { int maxSum = INT_MIN,sum; for(int i=0;i<M-1;i++) for(int j=0;j<N-1;j++) { sum = a[i][j]+a[i+1][j]+a[i][j+1]+a[i+1][j+1]; if(maxSum < sum) { maxSum = sum; res_i = i; res_j = j; } } return maxSum; }