[LeetCode]221. Maximal Square
2016-03-02 15:58
267 查看
Problem Description
Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing all 1’s and return its area.[]https://leetcode.com/problems/maximal-square/]
思路
DP!!用一个二维数组保存以(i,j)为右下角的最长边长,辣么,如果(i,j)是1,len(i,j)就是len(i-1,j),len(i,j-1),len(i-1,j-1)中的最小值+1、
状态转移方程就酱。。。
Code
package q221; public class Solution { public int maximalSquare(char[][] matrix) { int m=matrix.length; if(m<1) return 0; int n=matrix[0].length; if(n<0) return 0; int max=0; int[][] len=new int[m+1][n+1]; for(int i=0;i<m;i++){ if(matrix[i][0]=='1'){ len[i][0]=1; max=1; } else len[i][0]=0; } for(int i=0;i<n;i++){ if(matrix[0][i]=='1'){ len[0][i]=1; max=1; } else len[0][i]=0; } for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ if(matrix[i][j]=='1'){ len[i][j]=Math.min(Math.min(len[i-1][j], len[i][j-1]), len[i-1][j-1])+1; max=Math.max(max, len[i][j]); } else{ len[i][j]=0; } } } return max*max; } // public static void main(String[] args) { // // } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解