Problem:
Largest Square

Given a matrix (H × W) which contains only 1 and 0, find the area of the largest square matrix which only contains 0s.

Input

H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W

In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.

Output

Print the area (the number of 0s) of the largest square.

Constraints

1 ≤ H, W ≤ 1,400

Sample Input

4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0

Sample Output

4

Solution in JAVA (judge verdict: Memory Limit Exceeded)

import java.util.*;

class Main {
        public static void main(String args[]) {
                int H,W;
                int[][] map=new int[1400][1400];
                int i,j,k,x;
                try (Scanner sc = new Scanner(System.in)) {
                        H = sc.nextInt(); W = sc.nextInt();
                        for (i = 0; i < H; i++) {
                                for (j = 0; j < W; j++) {
                                        map[i][j] = sc.nextInt();
                                }
                        }
                }
                System.gc();

                for (i = 0; i < H; i++) {
                        j = 0;
                        while (j < W) {
                                k = j;
                                while (k < W && map[i][k] == 0) {
                                        k++;
                                }
                                for (x = (k==W?1:0); x <= k - j; x++) {
                                        map[i][k-x] = x;
                                }
                                j = k;
                                j++;
                        }
                }
                int ans = 0;
                for (i = 0; i < H; i++) {
                        for (j = 0; j < W; j++) {
                                if (map[i][j] > ans) {
                                        boolean f = true;
                                        for (k = i; k < i+ans+1 && k < H; k++) {
                                                if(map[k][j] <= ans) {
                                                        f = false;
                                                        break;
                                                }
                                        }
                                        if (f&&k==i+ans+1) {
                                                ans++;
                                                j--;
                                        }
                                }
                        }
                }
                System.out.println(ans*ans);
        }
}