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

Leetcode 221: Maximal Square

时间:2017-12-02 11:13:43      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:style   class   code   amp   var   i++   return   matrix   solution   

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

标签:style   class   code   amp   var   i++   return   matrix   solution   

原文地址:http://www.cnblogs.com/liangmou/p/7953370.html

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