首页 > 编程语言 > 详细

Java for LeetCode 221 Maximal Square

时间:2015-06-15 18:32:02      阅读:179      评论: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]作为右下节点的时候的最大矩形的边长,JAVA实现如下:

    public int maximalSquare(char[][] matrix) {
		if (matrix.length == 0 || matrix[0].length == 0)
			return 0;
		int res = 0;
		int[] dp = new int[matrix[0].length];
		for (int i = 0; i < matrix[0].length; i++)
			if (matrix[0][i] == ‘1‘){
				dp[i] = 1;
			    res=1;
			}
		for (int i = 1; i < matrix.length; i++) {
			dp[0] = matrix[i][0] == ‘1‘ ? 1 : 0;
			res=Math.max(res, dp[0]);
			for (int j = 1; j < matrix[0].length; j++) {
				if(matrix[i][j]==‘0‘)
					dp[j]=0;
				else if (dp[j] == dp[j - 1]
						&& matrix[i - dp[j]][j - dp[j]] == ‘0‘) {
					dp[j] = Math.min(dp[j], dp[j - 1]);
				} else
					dp[j] = Math.min(dp[j], dp[j - 1]) + 1;
				res=Math.max(res, dp[j]);
			}
		}
		return res*res;
    }

 

Java for LeetCode 221 Maximal Square

原文:http://www.cnblogs.com/tonyluis/p/4578743.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!