leetcode Maximal Square

来源:互联网 发布:免费商业源码分享 编辑:程序博客网 时间:2024/06/04 15:16

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 4.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

dp,递归关系式:dp[x][y]=min(dp[x-1][y],dp[x][y-1],dp[x-1][y-1])+1,dp[x][y]代表以x,y为右下顶点的正方形的最长边长,代码:

public int maximalSquare(char[][] matrix) {      int length=0;    int[][] res=new int[matrix.length+1][matrix[0].length+1];    for(int i=0;i<matrix.length;i++){        for(int j=0;j<matrix[0].length;j++){            if(matrix[i][j]=='1'){                res[i+1][j+1]=Math.min(Math.min(res[i][j+1],res[i+1][j]),res[i][j])+1;                if(res[i+1][j+1]>length) length=res[i+1][j+1];            }        }    }    return length*length;}

0 0
原创粉丝点击