LeetCode -- Maximal Square
Description:
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1
1 0 0 1 0
Return 4.
In a matrix, find the largest square area (1 indicates the point of the square, and 0 indicates null ).
This is a typical DP problem.
1. Assign dp [0, I] to matrix [0, I], dp [I, 0] To matrix [I, 0]. Iε [0, n)
2. Two-layer loops assign values to dp [I, j] based on different situations:
A. matrix [I, j] = 1 and 3 neighbors (dp [I-1, j], dp [I, J-1], dp [I-1, J-1]) are 1: dp [I, j] = 4
B. matrix [I, j] = 1 and three neighbors> 1 and equal: dp [I, j] = (square root of neighbor area + 1) Square
C. matrix [I, j] = 1 and 3 neighbors> = 1 but not necessarily equal: the square of dp [I, j] = (the square root of the minimum value of the neighbor + 1)
D. Other cases: dp [I, j] = matrix [I, j]
3. Use the max Variable to track the maximum value of the current dp [I, j ].
Implementation Code:
public class Solution { public int MaximalSquare(char[,] matrix) { var row = matrix.GetLength(0); var col = matrix.GetLength(1); if(row < 2){ if(row == 0){return 0;}else if(col == 1){return matrix[0,0] == '1' ? 1 : 0;} } var max = 0; var dp = new int[row, col]; for(var i = 0;i < row; i++){ var x = matrix[i,0] == '1' ? 1 : 0;dp[i, 0] = x;if(dp[i,0] > max){max = dp[i,0];} } for(var i = 0;i < col; i++){ var x = matrix[0,i] == '1' ? 1 : 0;dp[0, i] = x;if(dp[0,i] > max){max = dp[0,i];} } for(var i = 1;i < row; i++){ for(var j = 1;j < col; j++){// neighbours all equals 1 if(matrix[i,j] == '1' && dp[i-1,j] == 1 && dp[i, j-1] == 1 && dp[i-1,j-1] == 1){if(dp[i-1, j] == 1){dp[i,j] = 4;} }// neighbours all bigger than 1 and equals each otherelse if(matrix[i,j] == '1' && dp[i-1,j] == dp[i,j-1] && dp[i-1,j-1] == dp[i-1,j] && dp[i-1,j] > 1){dp[i,j] = (int)Math.Pow(Math.Sqrt(dp[i,j-1]) + 1,2);}// neighbours all no less than 1, but may not equals each otherelse if(matrix[i,j] == '1' && dp[i-1,j] >= 1 && dp[i,j-1] >= 1 && dp[i-1,j-1] >= 1){var min = Math.Min(Math.Min(dp[i-1,j-1], dp[i-1,j]), dp[i,j-1]);dp[i,j] = (int)Math.Pow(Math.Sqrt(min) + 1,2);} else{ dp[i,j] = matrix[i,j] == '1' ? 1 : 0; }if(dp[i,j] > max){max = dp[i,j];} } } return max; }}