Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from typing import List


class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
m, n = len(matrix), len(matrix[0])
dp = [[0] * n for _ in range(m)]
max_side = 0

for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
max_side = max(max_side, dp[i][j])

return max_side * max_side
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function maximalSquare(matrix: string[][]): number {
const m = matrix.length;
const n = matrix[0].length;
const dp: number[][] = Array.from({ length: m }, () => new Array(n).fill(0));
let maxSide = 0;

for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === '1') {
if (i === 0 || j === 0) {
dp[i][j] = 1;
} else {
dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1;
}
maxSide = Math.max(maxSide, dp[i][j]);
}
}
}

return maxSide * maxSide;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import unittest
from src.my_project.interviews.top_150_questions_round_22\
.ex_145_maximal_square import Solution


class MaximumSquareTestCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()

def test_example_1(self):
matrix = [
["1", "0", "1", "0", "0"],
["1", "0", "1", "1", "1"],
["1", "1", "1", "1", "1"],
["1", "0", "0", "1", "0"],
]
self.assertEqual(self.solution.maximalSquare(matrix), 4)

def test_example_2(self):
matrix = [["0", "1"], ["1", "0"]]
self.assertEqual(self.solution.maximalSquare(matrix), 1)

def test_example_3(self):
matrix = [["0"]]
self.assertEqual(self.solution.maximalSquare(matrix), 0)

def test_all_ones(self):
matrix = [["1", "1"], ["1", "1"]]
self.assertEqual(self.solution.maximalSquare(matrix), 4)


if __name__ == '__main__':
unittest.main()
Loading