Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created June 19, 2017 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yokolet/6855bc82a187fa8cd2316973bdbe03dd to your computer and use it in GitHub Desktop.
Save yokolet/6855bc82a187fa8cd2316973bdbe03dd to your computer and use it in GitHub Desktop.
public class MaximalSquare {
static int min(int a, int b, int c) {
return Math.min(a, Math.min(b, c));
}
static int findMaxSquare(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
int[][] memo = new int[n][m];
int max = 0;
// initialize
// copy first column
for (int i = 0; i < n; i++) {
memo[i][0] = matrix[i][0];
max = Math.max(max, memo[i][0]);
}
// copy first row
for (int i = 1; i < m; i++) {
memo[0][i] = matrix[0][i];
max = Math.max(max, memo[0][i]);
}
// fill the rest
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (matrix[i][j] == 1) {
memo[i][j] = min(memo[i - 1][j], memo[i - 1][j - 1], memo[i][j - 1]) + 1;
} else {
memo[i][j] = 0;
}
max = Math.max(max, memo[i][j]);
}
}
return max * max;
}
public static void main(String[] args) {
int[][] matrix = {
{1, 0, 1, 0, 0},
{1, 0, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 0, 0, 1, 0}
};
System.out.println(findMaxSquare(matrix));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment