221. Maximal Square

来源:互联网 发布:sql 报表开发工具 编辑:程序博客网 时间:2024/06/15 20:05

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

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 4.

Credits:

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

public class Solution {    public int maximalSquare(char[][] matrix) {        if (matrix == null || matrix.length == 0)return 0;int re = 0;for (int i = 0; i < matrix.length; ++i)if (matrix[i][0] == '1') {re = 1;break;}for (int i = 0; i < matrix[0].length; ++i) {if (matrix[0][i] == '1') {re = 1;break;}}for (int i = 1; i < matrix.length; ++i) {for (int j = 1; j < matrix[0].length; ++j) {if (matrix[i][j] == '0')continue;else {if (matrix[i - 1][j - 1] == '0')continue;int n = matrix[i - 1][j - 1] - '0';int m = 1;int plu = 1;while (m <= n) {if (matrix[i - m][j] != '0' && matrix[i][j - m] != '0') {plu += 1;m += 1;} elsebreak;}re = Math.max(re, plu);matrix[i][j] = (char) ('0' + plu);}}}return re * re;    }}