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.*;

public class Main {/* Largest Square */
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int h, w, maxS = 0;
		
		h = sc.nextInt();
		w = sc.nextInt();
		
		if(0 < h && h < 1401 && 0 < w && w < 1401){
			int[][] tiles = new int[h][w], map = new int[h][w];
			for(int i = 0; i < h; i++){
				for(int j = 0; j < w; j++){
					tiles[i][j] = sc.nextInt();/* ???????????? */
					map[i][j] = -1;/* ?????£????????\??????????????? */
				}
			}
		
			maxS = 0;
			for(int i = 0; i < h; i++){
				for(int j = 0; j < w;  j++){
					int ret = search(tiles, i, j, map);
					ret *= ret;
					if(ret > maxS){
						maxS = ret;
					}
				}
			}
		}else{
			maxS = 1;
		}
		sc.nextLine();
		System.out.println(maxS);		
	}
	
	public static int search(int[][] tiles, int i, int j, int[][] map){
		if(tiles[i][j] == 1){
			map[i][j] = 0;
			return 0;
		}else if(map[i][j] != -1){
			return map[i][j];
		}else{
			if(i + 1 < tiles.length && j + 1 < tiles[0].length){
				int min = search(tiles, i+1, j, map);
				int ret = search(tiles, i, j+1, map);
				if(ret < min){
					min = ret;
				}
				ret = search(tiles, i+1, j+1, map);
				if(ret < min){
					min = ret;
				}
				map[i][j] = min + 1;
				return map[i][j];				
			}else{
				map[i][j] = 1;
				return 1;
			}
		}
	}
}