Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input: 1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0Output: 4
难度:medium
题目:给定由0,1组成的矩阵,找出由1组成的最大方块并返回其面积。
思路:动态规划
转换方程grid[i][j] = Math.min(grid[i][j - 1], grid[i - 1][j], grid[i - 1][j - 1]) + 1 (matrix[i][j] = '1')Runtime: 7 ms, faster than 97.80% of Java online submissions for Maximal Square.
Memory Usage: 40.8 MB, less than 70.46% of Java online submissions for Maximal Square.class Solution { public int maximalSquare(char[][] matrix) { if (null == matrix || matrix.length < 1) { return 0; } int maxSquare = 0, m = matrix.length, n = matrix[0].length; int[][] grid = new int[m][n]; for (int i = 0; i < m; i++) { if ('1' == matrix[i][0]) { grid[i][0] = 1; maxSquare = 1; } } for (int i = 0; i < n; i++) { if ('1' == matrix[0][i]) { grid[0][i] = 1; maxSquare = 1; } } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { if ('1' == matrix[i][j]) { grid[i][j] = Math.min(grid[i - 1][j - 1], Math.min(grid[i - 1][j], grid[i][j - 1])) + 1; maxSquare = Math.max(maxSquare, grid[i][j]); } } } return maxSquare * maxSquare; }}