Maximal Square
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Here we are using brute force approach. We are using to variables - one maxlen -> which describes maximum square which is found so far and len -> which describes current square.
Whenever we found 1, we need to find maximum square with only 1's including current 1.
For this we are going to move rightwards and downwards, using temporary row index and column index.
If there is only 1, then loop goes until any 0 is found and maximum square is updated
Else if it contains 0, then last max square is updated and exits from temporary loop and this repeats, if there is any 1 found on matrix.
It also be solved easily with dynamic programing.
Please let us know your views in comment section
Example:
Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4
public class Solution {
public int maximalSquare(char[][] matrix) {
int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
int maxlen = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == '1') {
int len = 1;
boolean flag = true;
while (len + i < rows && len + j < cols && flag) {
for (int k = j; k <= len + j; k++) {
if (matrix[i + len][k] == '0') {
flag = false;
break;
}
}
for (int k = i; k <= len + i; k++) {
if (matrix[k][j + len] == '0') {
flag = false;
break;
}
}
if (flag)
len++;
}
if (maxlen < len) {
maxlen = len;
}
}
}
}
return maxlen * maxlen;
}
}
Try it on Leetcode
Here we are using brute force approach. We are using to variables - one maxlen -> which describes maximum square which is found so far and len -> which describes current square.
Whenever we found 1, we need to find maximum square with only 1's including current 1.
For this we are going to move rightwards and downwards, using temporary row index and column index.
If there is only 1, then loop goes until any 0 is found and maximum square is updated
Else if it contains 0, then last max square is updated and exits from temporary loop and this repeats, if there is any 1 found on matrix.
It also be solved easily with dynamic programing.
Please let us know your views in comment section
Comments
Post a Comment