MaxArea-最大矩阵

MaxArea-最大矩阵

几道最大区域(矩形)相关的题。
题目一:

container-with-most-water
Given n non-negative integers a1 , a2 , …, an , where each represents a point at coordinate (i, ai ). n vertical lines are drawn such that the two endpoints of line i is at (i, ai ) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.

题目二:
比较常见经典的一道题,求直方图的最大矩形

题目三:

maximal-rectangle
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.
例如二维数组矩阵:
[[1, 1, 0, 0, 1],
[0, 1, 0, 0, 1],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1],
[0, 0, 0, 0, 1]]
输出6

下面直接上代码,代码可能更直观

import java.util.*;

public class MaxArea {


    //两边和x轴构成的container最大
    //height[i]之间宽为1
    //初始low=0,high=height.length-1,不断淘汰短的一边(以该边为边的最大container为当前area),宽度不断减小
    //height[low]>height[high]时,比当前大的area,双边肯定在 low~high-1 之间选择
    //O(n)
    public static int maxArea(int[] height) {
        int low=0,high=height.length-1;
        int area =0,max=0;
        while(low<high){
            area=Math.max(area,(high-low)*Math.min(height[low],height[high]));
            if(height[low]>height[high])
                high--;
            else if(height[low]<height[high])
                low++;
            else{
                low++;
                high--;
            }
        }
        return area;
    }


    //直方图最大矩形,O(n)
    //主要思路:实际是中心扩展法的优化
    // j<i,heights[j]遇到更小的heights[i]时,可以求以j,heights[j]为高的最大矩形(以heights[j]为限制高,向两侧扩展)
    public static int largestRectangleArea(int[] heights) {
        if(heights==null||heights.length==0)
            return 0;
        int res=0;
        Stack<Integer> stack=new Stack<>();
        for(int i=0;i<heights.length;i++){
            while(!stack.isEmpty()&&heights[i]<=heights[stack.peek()]){
                int cur=stack.pop();
                int left=stack.isEmpty()?-1:stack.peek();
                res=Math.max(res,(i-left-1)*heights[cur]);
            }
            stack.push(i);
        }
        while(!stack.isEmpty()){
            int cur=stack.pop();
            int left=stack.isEmpty()?-1:stack.peek();
            res=Math.max(res,(heights.length-left-1)*heights[cur]);
        }
        return res;
    }

    //O(n*n)
    //添加转换:
    //    0 0 1 1 0 -> 0 0 1 1 0
    //    0 0 1 1 0 -> 0 0 2 2 0
    //    1 1 0 0 0 -> 1 1 0 0 0
    //    1 1 1 0 0 -> 2 2 1 0 0
    //再以每一行为底去求最大矩形
    public static int maximalRectangle(char[][] matrix) {

        if (matrix == null || matrix[0].length == 0) {
            return 0;
        }

        int[][] dp=new int[matrix.length][matrix[0].length];
        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[0].length;j++)
            if(i==0){
                dp[i][j]=matrix[i][j]=='1'?1:0;
            }else{
                dp[i][j]=matrix[i][j]=='0'?0:dp[i-1][j]+1;
            }
        }

        int max=0;
        for(int i=0;i<matrix.length;i++){
            int temp=largestRectangleArea(dp[i]);
            max=Math.max(max,temp);
        }
        return max;

    }

}

### 在 MATLAB 中检测和裁剪图像的最大内接矩形 为了实现这一目标,可以采用基于边缘检测的方法来识别图像中的对象轮廓,并从中找出最大的内接矩形。下面介绍了一种可能的技术路径: #### 边缘检测与二值化处理 首先读入待处理的图片并转换成灰度模式以便后续操作更加简便高效。 ```matlab img = imread('example_image.png'); grayImg = rgb2gray(img); bwImg = edge(grayImg, 'Canny'); % 使用 Canny 算法进行边缘检测 ``` #### 轮廓查找及筛选 接着利用 `bwboundaries` 函数获取所有封闭边界的信息,之后遍历这些边界寻找满足条件的最佳候选者—即面积最大且形状接近矩形的对象。 ```matlab [B,L] = bwboundaries(bwImg, 'noholes'); stats = regionprops(L, {'Area', 'BoundingBox'}); max_area = 0; best_rect = []; for i=1:length(stats) area = stats(i).Area; bbox = stats(i).BoundingBox; if (area > max_area && ... abs(bbox(3)-bbox(4))<min(bbox(3),bbox(4))*0.5) % 控制宽高比例差异不超过一半 best_rect = [round(bbox(1)), round(bbox(2)), round(bbox(3)), round(bbox(4))]; max_area = area; end end ``` 上述代码片段中定义了一个简单的规则用于判断当前包围盒是否更适合作为目标矩形:不仅考虑其占据的空间大小(`area`),还加入了宽度高度之间的相对差距作为辅助标准以排除那些明显偏离正方形形态的选择[^3]。 #### 图像裁剪展示 最后按照选定出来的最优矩形参数执行实际切割动作,并将原始图同截取后的部分一同呈现出来供对比查看。 ```matlab croppedImage = imcrop(img,best_rect); figure; subplot(1,2,1); imshow(img); hold on ; rectangle('Position',best_rect,'EdgeColor','r','LineWidth',2); title('Original Image with Detected Rectangle'); subplot(1,2,2); imshow(croppedImage); title('Cropped Largest Inner Rectangle'); ``` 此过程综合运用了几何分析手段以及图像处理技术,在保持较高精度的同时实现了自动化定位并提取感兴趣区域内最合适的矩形区域的目的[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值