Skip to content

Commit 580f5fb

Browse files
author
0x01f7
committed
solve: Maximal Square
1 parent cf46d45 commit 580f5fb

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777
| 224 | [Basic Calculator][p224] | [Ruby][s224] | Medium |
7878
| 223 | [Rectangle Area][p223] | [Ruby][s223] | Easy |
7979
| 222 | [Count Complete Tree Nodes][p222] | [Ruby][s222] | Medium |
80-
| 221 | [Maximal Square][p221] | | Medium |
80+
| 221 | [Maximal Square][p221] | [Ruby][s221] | Medium |
8181
| 220 | [Contains Duplicate III][p220] | [Ruby][s220] | Medium |
8282
| 219 | [Contains Duplicate II][p219] | [Ruby][s219] | Easy |
8383
| 218 | [The Skyline Problem][p218] | | Hard |
@@ -605,6 +605,7 @@
605605
[s224]:./algorithms/basic_calculator.rb
606606
[s223]:./algorithms/rectangle_area.rb
607607
[s222]:./algorithms/count_complete_tree_nodes.rb
608+
[s221]:./algorithms/maximal_square.rb
608609
[s220]:./algorithms/contains_duplicate_iii.rb
609610
[s219]:./algorithms/contains_duplicate_ii.rb
610611
[s217]:./algorithms/contains_duplicate.rb

algorithms/maximal_square.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

0 commit comments

Comments
 (0)