首页 > 其他分享 >LeetCode: 221. Maximal Square

LeetCode: 221. Maximal Square

时间:2022-12-05 18:06:04浏览次数:44  
标签:Maximal Square matrix int ++ ans LeetCode size


LeetCode: 221. Maximal Square

题目描述

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 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output:​4​

解题思路 —— 动态规划

利用动态规划,将 ​​(i, j)​​​ 问题转换为 ​​(i-1, j)​​​,​​(i, j-1)​​​ 和 ​​(i-1, j-1)​​ 三个子问题。

AC 代码

class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int ans = 0;

for(int i = 1; i < matrix.size(); ++i)
{
for(int j = 1; j < matrix[i].size(); ++j)
{
if(matrix[i][j] == '1')
{
matrix[i][j] = min(min(matrix[i][j-1], matrix[i-1][j]), matrix[i-1][j-1])+1;
}
}
}

for(int i = 0; i < matrix.size(); ++i)
{
for(int j = 0; j < matrix[i].size(); ++j)
{
ans = max(ans, matrix[i][j]-'0');
}
}

return ans*ans;
}
};


标签:Maximal,Square,matrix,int,++,ans,LeetCode,size
From: https://blog.51cto.com/u_15903085/5913200

相关文章

  • LeetCode: 223. Rectangle Area
    LeetCode:223.RectangleArea题目描述Findthetotalareacoveredbytworectilinearrectanglesina2Dplane.Eachrectangleisdefinedbyitsbottomleftcorne......
  • LeetCode: 225. Implement Stack using Queues
    LeetCode:225.ImplementStackusingQueues题目描述Implementthefollowingoperationsofastackusingqueues.​​push(x)​​–Pushelementxontostack.​......
  • LeetCode: 232. Implement Queue using Stacks
    LeetCode:232.ImplementQueueusingStacks题目描述Implementthefollowingoperationsofaqueueusingstacks.​​push(x)​​​–Pushelementxtothebacko......
  • LeetCode: 227. Basic Calculator II
    LeetCode:227.BasicCalculatorII题目描述Implementabasiccalculatortoevaluateasimpleexpressionstring.Theexpressionstringcontainsonlynon-negative......
  • LeetCode: 239. Sliding Window Maximum
    LeetCode:239.SlidingWindowMaximum题目描述Givenanarraynums,thereisaslidingwindowofsizekwhichismovingfromtheveryleftofthearraytotheve......
  • LeetCode: 228. Summary Ranges
    LeetCode:228.SummaryRanges题目描述Givenasortedintegerarraywithoutduplicates,returnthesummaryofitsranges.Example1:Input:[0,1,2,4,5,7]Output:[......
  • LeetCode: 234. Palindrome Linked List
    LeetCode:234.PalindromeLinkedList题目描述Givenasinglylinkedlist,determineifitisapalindrome.Example1:Input:1->2Output:falseExample2:Input:1->......
  • LeetCode: 241. Different Ways to Add Parentheses
    LeetCode:241.DifferentWaystoAddParentheses题目描述Givenastringofnumbersandoperators,returnallpossibleresultsfromcomputingallthedifferentp......
  • LeetCode: 238. Product of Array Except Self
    LeetCode:238.ProductofArrayExceptSelf题目描述Givenanarraynumsofnintegerswhere​​n>1​​​,returnanarrayoutputsuchthatoutput[i]isequal......
  • LeetCode: 242. Valid Anagram
    LeetCode:242.ValidAnagram题目描述Giventwostrings​​s​​​and​​t​​​,writeafunctiontodetermineiftisananagramof​​s​​.Example1:Inp......