Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement