221. Maximal Square

题目:

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 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Return 4.

链接: http://leetcode.com/problems/maximal-square/

7/19/2017

看答案做的

 1 public class Solution {
 2     public int maximalSquare(char[][] matrix) {
 3         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
 4             return 0;
 5         }
 6         int[] dp = new int[matrix[0].length + 1];
 7         int maxLen = 0;
 8         int prev = 0;
 9         for (int i = 1; i <= matrix.length; i++) {
10             for (int j = 1; j <= matrix[0].length; j++) {
11                 int temp = dp[j];
12                 if (matrix[i - 1][j - 1] == '1') {
13                     dp[j] = Math.min(Math.min(dp[j - 1], prev), dp[j]) + 1;
14                     maxLen = Math.max(maxLen, dp[j]);
15                 } else {
16                     dp[j] = 0;
17                 }
18                 prev = temp;
19             }
20         }
21         return maxLen * maxLen;
22     }
23 }

官方答案

https://leetcode.com/problems/maximal-square/#/solution

更多讨论

https://discuss.leetcode.com/category/229/maximal-square

posted @ 2017-07-20 10:21  panini  阅读(235)  评论(0编辑  收藏  举报