火柴拼出多少个正方形 http://matchstickpuzzles.blogspot.com/2011/06/55-4x4-square-how-many-squares.html
输入是两个二维数组ver 和 hor, 若是有火柴就是1, 没有就是0.
dpHor 表示横方向上有多少连续火柴,dpVer表示纵方向上有多少连续火柴。
最后以左上角第一根横着的火柴为根基检查是否能组成正方形。
Time Complexity: O(n^3). Space: O(n^2).
import java.util.*;
public class countSquare{
public static void main(String [] args){
int [][] hor = {{1,1},{1,0},{1,1}};
int [][] ver = {{1,1,1},{1,1,1}};
System.out.println("Number of square: " + countSquare(hor,ver));
} private static int countSquare(int [][] hor, int [][] ver){
if(hor == null || ver == null || hor.length == 0 || ver.length == 0 || hor[0].length == 0 || ver[0].length == 0){
return 0;
} int [][] dpHor = new int[hor.length][hor[0].length];
int [][] dpVer = new int[ver.length][ver[0].length]; for(int i = 0; i<hor.length; i++){
for(int j = 0; j<hor[0].length; j++){
if(hor[i][j] == 1){
dpHor[i][j] = j == 0 ? 1 : dpHor[i][j-1] + 1;
}else{
dpHor[i][j] = 0;
}
}
} for(int j = 0; j<ver[0].length; j++){
for(int i = 0; i<ver.length; i++){
if(ver[i][j] == 1){
dpVer[i][j] = i == 0 ? 1 : dpVer[i-1][j] + 1;
}else{
dpVer[i][j] = 0;
}
}
} System.out.println("dpHor is " + Arrays.deepToString(dpHor));
System.out.println("dpVer is " + Arrays.deepToString(dpVer)); int res = 0;
for(int i = 0; i<hor.length; i++){
for(int j = 0; j<hor[0].length; j++){
for(int len = 1; len<= Math.min(ver.length-i, hor[0].length-j); len++){
if(dpHor[i][j+len-1] >= len && dpHor[i+len][j+len-1] >= len && dpVer[i+len-1][j] >= len && dpVer[i+len-1][j+len] >= len){
res++;
System.out.println("i = " + i + ", j = " + j + ", len = " + len + ", res = " + res);
}
}
}
}
return res;
}
}