Interview How to Count Squares
火柴拼出多少个正方形 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).
1 import java.util.*; 2 public class countSquare{ 3 public static void main(String [] args){ 4 int [][] hor = {{1,1},{1,0},{1,1}}; 5 int [][] ver = {{1,1,1},{1,1,1}}; 6 System.out.println("Number of square: " + countSquare(hor,ver)); 7 } 8 9 private static int countSquare(int [][] hor, int [][] ver){ 10 if(hor == null || ver == null || hor.length == 0 || ver.length == 0 || hor[0].length == 0 || ver[0].length == 0){ 11 return 0; 12 } 13 14 int [][] dpHor = new int[hor.length][hor[0].length]; 15 int [][] dpVer = new int[ver.length][ver[0].length]; 16 17 for(int i = 0; i<hor.length; i++){ 18 for(int j = 0; j<hor[0].length; j++){ 19 if(hor[i][j] == 1){ 20 dpHor[i][j] = j == 0 ? 1 : dpHor[i][j-1] + 1; 21 }else{ 22 dpHor[i][j] = 0; 23 } 24 } 25 } 26 27 for(int j = 0; j<ver[0].length; j++){ 28 for(int i = 0; i<ver.length; i++){ 29 if(ver[i][j] == 1){ 30 dpVer[i][j] = i == 0 ? 1 : dpVer[i-1][j] + 1; 31 }else{ 32 dpVer[i][j] = 0; 33 } 34 } 35 } 36 37 System.out.println("dpHor is " + Arrays.deepToString(dpHor)); 38 System.out.println("dpVer is " + Arrays.deepToString(dpVer)); 39 40 int res = 0; 41 for(int i = 0; i<hor.length; i++){ 42 for(int j = 0; j<hor[0].length; j++){ 43 for(int len = 1; len<= Math.min(ver.length-i, hor[0].length-j); len++){ 44 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){ 45 res++; 46 System.out.println("i = " + i + ", j = " + j + ", len = " + len + ", res = " + res); 47 } 48 } 49 } 50 } 51 return res; 52 } 53 }