29. 微软面试题:求一个矩阵中最大的二维矩阵(元素和最大)

题目:求一个矩阵中最大的二维矩阵(元素和最大).如:
1 2 0 3 4
2 3 4 5 1
1 1 5 3 0
中最大的是:
4 5
5 3

要求:(1)写出算法;(2)分析时间复杂度;(3)用C写出关键代码


分析:

直接遍历二维数组,求出最大的二维数组就OK了


实现如下:

#include<iostream>

using namespace std;

int max_matrix(int (*array)[5], int maxx, int maxy, int& posi, int& posj)
{
        int max = 0;
        int i = 0, j = 0;
        while(i < maxx - 1)
        {
                j = 0;
                while( j < maxy - 1)
                {
                        int t = array[i][j] + array[i+1][j] + array[i][j+1] + array[i+1][j+1];
                        if( max < t)
                        {
                                max = t;
                                posi = i;
                                posj = j;
                        }
                        j ++;
                }
                i ++;
        }
        return max;
}

int main()
{
        int a[3][5] = {{1,2,0,3,4}, {2,3,4,5,1}, {1,1,5,3,0}};
        int i = 0, j = 0;
        int max = max_matrix(a, 3, 5, i, j);
        cout << "max num: " << max <<endl;
        cout << "matrix: " << endl;
        cout << a[i][j] << " " << a[i][j+1] << endl;
        cout << a[i+1][j] << " " << a[i+1][j+1] << endl;

}

输出如下:

max num: 17
matrix: 
4 5
5 3

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值