Leetcode 221: Maximal Square

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

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.

 

 1 public class Solution {
 2     public int MaximalSquare(char[,] matrix) {
 3         int rows = matrix.GetLength(0), cols = matrix.GetLength(1);
 4         
 5         var dp = new int[rows + 1, cols + 1];
 6         int max = 0;
 7         
 8         for (int i = 0; i < rows; i++)
 9         {
10             for (int j = 0; j < cols; j++)
11             {
12                 if (matrix[i, j] == 0)
13                 {
14                     dp[i + 1, j + 1] = 0;
15                 }
16                 else
17                 {
18                     dp[i + 1, j + 1] = Math.Min(Math.Min(dp[i, j + 1], dp[i + 1, j]), dp[i, j]) + 1;
19                     max = Math.Max(max, dp[i + 1, j + 1]);
20                 }
21             }
22         }
23         
24         return max * max;
25     }
26 }

 

以上是关于Leetcode 221: Maximal Square的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 221: Maximal Square

[Leetcode] 221. Maximal Square

[Leetcode221]最大面积 Maximal Square

[LeetCode] 221. Maximal Square 最大正方形

(DP 线性DP) leetcode 221. Maximal Square

leetcode 221. Maximal Square 最大正方形(中等)