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;
                try (Scanner sc = new Scanner(System.in)) {
                        H = sc.nextInt(); W = sc.nextInt();
                        map = new int[H][W];
                        for (int i = 0; i < H; i++) {
                                for (int j = 0; j < W; j++) {
                                        map[i][j] = sc.nextInt();
                                }
                        }
                }
                System.gc();

                int i,j,k,x;
                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--;
                                        }
                                }
                        }
                }
                ans = Math.max(ans * ans, 0);
                System.out.println(ans);
        }
}