221. Maximal Square Java Solutions

Source: Internet
Author: User

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

For example, given the following matrix:

1 1 1 1 11 0 0 1 0

Return 4.

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

The title is to find the largest square with an element that is all 1. Using DP, the recursive type is:

DP[I][J] = Math.min (Dp[i-1][j],math.min (dp[i][j-1],dp[i-1][j-1])) + 1;

DP[I][J] Indicates the length of the square that appears at that position, dp[i][j] to form a new square, only from the previous left, upper, top left three inside to take the edge length of the smallest plus matrix[i][j] 1, that is, edge length +1.
1  Public classSolution {2      Public intMaximalsquare (Char[] matrix) {3         if(Matrix = =NULL|| Matrix.length = = 0 | | Matrix[0].length = = 0)return0;4         intm = Matrix.length,n = Matrix[0].length;5         int[] DP =New int[m][n];6         intLen = 0;7          for(inti = 0; i<m; i++){8             if(matrix[i][0] = = ' 1 '){9Dp[i][0] = 1;TenLen = 1; One             } A         } -          for(inti = 0; i<n; i++){ -             if(Matrix[0][i] = = ' 1 '){ theDp[0][i] = 1; -Len = 1; -             } -         } +          for(inti = 1; I < m; i++){ -              for(intj = 1; J < N; J + +){ +                 if(Matrix[i][j] = = ' 1 '){ ADP[I][J] = Math.min (Dp[i-1][j],math.min (dp[i][j-1],dp[i-1][j-1])) + 1; atlen = dp[i][j] > len?Dp[i][j]: len; -                 } -             } -         } -         returnlen*Len; -     } in}

221. Maximal Square Java Solutions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.