码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Maximal Square

时间:2015-12-19 01:26:02      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

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.

dp问题,用一个dp[i][j]保存matrix[i][j]作为右下节点的时候的最大矩形的边长

if (matrix[i][j] == ‘0‘) dp[i][j] = 0;

else dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;

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

 

Leetcode: Maximal Square

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5058543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!