topic:
Thought:
可以使用Dynamic planning降低时间复杂度。we use dp(i,j) Express (i,j) The lower right corner,Only contain 1 The maximum value of the side length of the square。If we can calculate all dp(i,j) Value,Then the maximum value is that it is only included in the matrix 1 The maximum value of the side length of the square,其平方即为Maximum square的面积。
So how to calculate dp Each element value?For each position (i,j),检查在矩阵中该位置Value:
if该位置Value是 0,but dp(i,j)=0,Because the current location cannot 1 Folk formation of composition;
if该位置Value是 1,but dp(i,j) Value由其上方、Three adjacent locations on the left and upper left dp Value decision。in particular,The element value of the current position is equal to the minimum value of the three adjacent elements 1,The state transfer equation is as follows:
dp(i,j)=min(dp(i−1,j),dp(i−1,j−1),dp(i,j−1))+1
also,You also need to consider boundary conditions。if i and j At least one of them is 0,but以位置(i,j) The lower right corner的Maximum square的边长只能是 1,therefore dp(i,j)=1
Code:
1 | package main |