Java for LeetCode 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.

解题思路:

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;
    }

 

posted @ 2015-06-15 17:26  TonyLuis  阅读(459)  评论(0编辑  收藏  举报