【LeetCode】 221. Maximal Square
Description
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
給予一個二維的二元陣列,其元素只有0和1。找到由1構成的最大正方形並回傳它的面積。
Example:
Solution
- 先注意一件事情,他給的二元矩陣不是用
int
也不是bool
,竟然是用char
。(我沒注意到這個,找bug找好久QQ)
- 方法一是直接暴力破解,聽說可以過,但我沒有試過。
- 比較好的解法是使用DP。建一個表格,初始化和原來的矩陣一樣。
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
- 畫個圖來理解一下,當紅色都是
1
,藍色都是1
,綠色也都是1
時,如果右下角(黃色)也是1
,就可以變成一個大的正方形。
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
- 換句話說,當左上、上、左都是
x
的時候,如果自己為1
,就可以組成一個x + 1
的正方形。
- 遞迴式:
- 整理後可以發現,DP和原矩陣可以直接合併,最後時間複雜度為
O(mn)
,空間複雜度O(1)
。
Code