How many squares does a match spell http://matchstickpuzzles.blogspot.com/2011/06/55-4x4-square-how-many-squares.html
The input is two-dimensional array ver and hor, if there is a match is 1, not 0.
Dphor indicates how many consecutive matches are in the transverse direction, and Dpver indicates how many consecutive matches are in the longitudinal direction.
Finally, the top left corner of the first transverse match as the basis to check whether to form a square.
Time Complexity:o (n^3). Space:o (n^2).
1 ImportJava.util.*;2 Public classcountsquare{3 Public Static voidmain (String [] args) {4 int[] Hor = {{1,1},{1,0},{1,1}};5 int[] ver = {{1,1,1},{1,1,1}};6System.out.println ("Number of square:" +Countsquare (Hor,ver));7 }8 9 Private Static intCountsquare (int[] Hor,int[] ver) {Ten if(Hor = =NULL|| ver = =NULL|| Hor.length = = 0 | | Ver.length = = 0 | | Hor[0].length = = 0 | | Ver[0].length = = 0){ One return0; A } - - int[] Dphor =New int[Hor.length] [Hor[0].length]; the int[] Dpver =New int[Ver.length] [Ver[0].length]; - - for(inti = 0; i){ - for(intj = 0; j){ + if(Hor[i][j] = = 1){ -DPHOR[I][J] = j = = 0? 1:DPHOR[I][J-1] + 1; +}Else{ ADPHOR[I][J] = 0; at } - } - } - - for(intj = 0; j<ver[0].length; J + +){ - for(inti = 0; i<ver.length; i++){ in if(Ver[i][j] = = 1){ -DPVER[I][J] = i = = 0? 1:DPVER[I-1][J] + 1; to}Else{ +DPVER[I][J] = 0; - } the } * } $ Panax NotoginsengSystem.out.println ("Dphor is" +arrays.deeptostring (Dphor)); -System.out.println ("Dpver is" +arrays.deeptostring (Dpver)); the + intres = 0; A for(inti = 0; i){ the for(intj = 0; j){ + for(intlen = 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); - } - } the } - }Wuyi returnRes; the } -}
Interview How to Count squares