1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
static int countRectangles(int[][] matrix) { int count = 0; boolean counted = false; for(int n=0; n<matrix.length; n++) { //rows for(int m=0; m<matrix.length; m++) { //columns counted = false; //rectangle found. detect its borders. if(matrix[n][m] == 1) { //rectangle cells set to -1, to avoid double-calculating. matrix[n][m] = -1; int tempM = m, tempN = n, cols = 1; //count of columns in the rectangle B: while(counted==false) { if( ((tempM+1) < matrix.length) && (matrix[n][tempM+1]== 1) ) { matrix[n][tempM+1] = -1; cols++; tempM++; continue B; } if( ((tempN+1) < matrix.length) && (matrix[tempN+1][m]== 1) ) { for(int k=0; k<cols; k++) { matrix[tempN+1][m+k]= -1; } tempN++; continue B; } counted = true; //all cells of the rectangle found. } count++; } } } return count; } |