标签:
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.
思路:
动态规划
我的代码:
public class Solution { public int maximalSquare(char[][] matrix) { if(matrix==null || matrix.length==0 || matrix[0].length==0) return 0; int row = matrix.length; int col = matrix[0].length; int max = 0; int[][] square = new int[row][col]; //first row for(int i=0; i<row; i++) square[i][0] = matrix[i][0]-‘0‘; //first col for(int j=0; j<col; j++) square[0][j] = matrix[0][j]-‘0‘; for(int i=1; i<row; i++) { for(int j=1; j<col; j++) { if(matrix[i][j] == ‘0‘) square[i][j] = 0; else square[i][j] = Math.min(Math.min(square[i-1][j], square[i][j-1]), square[i-1][j-1])+1; } } for(int i=0; i<row; i++) { for(int j=0; j<col; j++) { max = Math.max(max, square[i][j]); } } return max*max; } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4551166.html