File tree Expand file tree Collapse file tree 2 files changed +40
-1
lines changed Expand file tree Collapse file tree 2 files changed +40
-1
lines changed Original file line number Diff line number Diff line change 77
77
| 224 | [ Basic Calculator] [ p224 ] | [ Ruby] [ s224 ] | Medium |
78
78
| 223 | [ Rectangle Area] [ p223 ] | [ Ruby] [ s223 ] | Easy |
79
79
| 222 | [ Count Complete Tree Nodes] [ p222 ] | [ Ruby] [ s222 ] | Medium |
80
- | 221 | [ Maximal Square] [ p221 ] | | Medium |
80
+ | 221 | [ Maximal Square] [ p221 ] | [ Ruby ] [ s221 ] | Medium |
81
81
| 220 | [ Contains Duplicate III] [ p220 ] | [ Ruby] [ s220 ] | Medium |
82
82
| 219 | [ Contains Duplicate II] [ p219 ] | [ Ruby] [ s219 ] | Easy |
83
83
| 218 | [ The Skyline Problem] [ p218 ] | | Hard |
605
605
[ s224 ] :./algorithms/basic_calculator.rb
606
606
[ s223 ] :./algorithms/rectangle_area.rb
607
607
[ s222 ] :./algorithms/count_complete_tree_nodes.rb
608
+ [ s221 ] :./algorithms/maximal_square.rb
608
609
[ s220 ] :./algorithms/contains_duplicate_iii.rb
609
610
[ s219 ] :./algorithms/contains_duplicate_ii.rb
610
611
[ s217 ] :./algorithms/contains_duplicate.rb
Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/maximal-square/
2
+ #
3
+ # Given a 2D binary matrix filled with 0's and 1's, find the largest
4
+ # square containing all 1's and return its area.
5
+ #
6
+ # For example, given the following matrix:
7
+ #
8
+ # 1 0 1 0 0
9
+ # 1 0 1 1 1
10
+ # 1 1 1 1 1
11
+ # 1 0 0 1 0
12
+ #
13
+ # Return 4.
14
+
15
+
16
+ # @param {Character[][]} matrix
17
+ # @return {Integer}
18
+ def maximal_square ( matrix )
19
+ return 0 if matrix . empty?
20
+
21
+ m , n = matrix . size , matrix [ 0 ] . size
22
+ dp = Array . new ( m ) { Array . new ( n , 0 ) }
23
+
24
+ maxwidth = 0
25
+
26
+ 0 . upto ( m - 1 ) do |i |
27
+ 0 . upto ( n - 1 ) do |j |
28
+ if i == 0 || j == 0 || matrix [ i ] [ j ] == '0'
29
+ dp [ i ] [ j ] = matrix [ i ] [ j ] . to_i
30
+ else
31
+ dp [ i ] [ j ] = [ dp [ i - 1 ] [ j - 1 ] , dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ] . min + 1
32
+ end
33
+ maxwidth = dp [ i ] [ j ] if maxwidth < dp [ i ] [ j ]
34
+ end
35
+ end
36
+
37
+ maxwidth * maxwidth
38
+ end
You can’t perform that action at this time.
0 commit comments