码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_221题——Maximal Square (动态规划)

时间:2015-07-10 11:00:27      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

Maximal Square

 Total Accepted: 6373 Total Submissions: 31927My Submissions

 

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.

 

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

 

Hide Tags
 Dynamic Programming
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

 

dp[x][y] = min(dp[x - 1][y - 1], dp[x][y - 1], dp[x - 1][y]) + 1
#include<iostream>
#include<vector>
#include<math.h>
using namespace std;

int maximalSquare(vector<vector<char>>& matrix)
{
	if(matrix.empty())
		return 0;

	int m=matrix.size();
	int n=matrix[0].size();
	vector<vector<int>> ma;
	vector<int> ve;
	for(int i=0;i<n;i++)
		ve.push_back(0);
	for(int i=0;i<m;i++)
	{
		ma.push_back(ve);
	}
	int re=0;
	for(int i=0;i<n;i++)
	{
		if(matrix[0][i]==‘1‘)
			{
				ma[0][i]=1;
				re=1;
		}
		else
			ma[0][i]=0;
	}
	for(int j=0;j<m;j++)
	{
		if(matrix[j][0]==‘1‘)
			{
				ma[j][0]=1;
				re=1;
		}
		else
			ma[j][0]=0;
	}
	if(m==1)
		return re;

	for(int i=1;i<m;i++)
	{
		for(int j=1;j<n;j++)
		{
			if(matrix[i][j]==‘1‘)
			{
				ma[i][j]=min(min(ma[i][j-1],ma[i-1][j]),ma[i-1][j-1])+1;
				if(re<ma[i][j])
					re=ma[i][j];
			}
			else
				ma[i][j]=0;
		}
	}
	return re*re;
}
int main()
{
	vector<vector<char>> matrix;
	vector<char> ma;
	ma.push_back(‘0‘);
	matrix.push_back(ma);
	cout<<maximalSquare(matrix)<<endl;

}

  

 

leetcode_221题——Maximal Square (动态规划)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4634900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!