leetcode_221문항-Maximal Square(동적 기획)

3109 단어 LeetCode
Maximal Square  
Total Accepted: 6373 Total Submissions: 31927 My Submissions
Question
 Solution 
 
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;



}


  
 

좋은 웹페이지 즐겨찾기