程序员代码面试指南刷题--第一章.求最大子矩阵的大小

题目描述

给定一个整型矩阵 map,其中的值只有 0 和 1 两种,求其中全是 1 的所有矩形区域中,最大的矩形区域里 1 的数量。

输入描述:

第一行输入两个整数 n 和 m,代表 nm 的矩阵
接下来输入一个 n
m 的矩阵

输出描述:

输出其中全是 1 的所有矩形区域中,最大的矩形区域里 1 的数量。

示例1
输入

1 4
1 1 1 0

输出

3

说明

最大的矩形区域有3个1,所以返回3

解法一:利用单调栈

import java.io.*;
import java.util.*;
public class Main{
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] s1 = br.readLine().trim().split(" ");
        int r = Integer.parseInt(s1[0]);
        int c = Integer.parseInt(s1[1]);
        int[][] map = new int[r][c];
        for(int i=0;i<r;i++){
            String[] s2 = br.readLine().trim().split(" ");
            for(int j=0;j<c;j++){
                map[i][j] = Integer.parseInt(s2[j]);
            }
        }
        int res = func(map);
        System.out.println(res);
    }
    public static int func(int[][] map){
        if(map==null||map.length==0||map[0].length==0){
            return 0;
        }
        int[] height = new int[map[0].length];
        int max = 0;
        for(int i=0;i<map.length;i++){
            for(int j=0;j<height.length;j++){
                height[j] = map[i][j]==0?0:height[j]+1;
            }
            int tmp = maxMatrix(height);
            if(tmp>max){
                max = tmp;
            }
        }
        return max;
    }
    public static int maxMatrix(int[] height){
        if(height==null||height.length==0){
            return 0;
        }
        Stack<Integer> s = new Stack<>();
        int max = 0;
        for(int i=0;i<height.length;i++){
            while(!s.isEmpty()&&height[s.peek()]>=height[i]){
                int index = s.pop();
                int a = height[index]; //宽
                int b = s.isEmpty()?i:i-s.peek()-1;//长
                int maxtmp = a*b;
                max = max<maxtmp?maxtmp:max;
            }
            s.push(i);
        }
        while(!s.isEmpty()){
            int tmpindex = s.pop();
            int a = height[tmpindex]; //宽
            int b = s.isEmpty()?height.length:height.length-s.peek()-1;//长
            int maxtmp = a*b;
            max = max<maxtmp?maxtmp:max;
        }
        return max;
    }
}

解法二:暴力。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值