hope it could help someone
package com.codegym.task.task20.task2026;
/*
Rectangle algorithms
*/
public class Solution {
public static void main(String[] args) {
byte[][] a1 = new byte[][]{
{1, 1, 0, 0},
{1, 1, 0, 0},
{1, 1, 0, 0},
{1, 1, 0, 1}
};
byte[][] a2 = new byte[][]{
{1, 0, 0, 1},
{0, 0, 0, 0},
{0, 0, 0, 0},
{1, 0, 0, 1}
};
int count1 = getRectangleCount(a1);
System.out.println("count = " + count1 + ". Must be 2");
int count2 = getRectangleCount(a2);
System.out.println("count = " + count2 + ". Must be 4");
}
public static int getRectangleCount(byte[][] a) {
int count = 0;
int startRow = -1;
int startColumn = -1;
int endRow = -1;
int endColumn = -1;
int width = -1;
int height = -1;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] == 0 && (width + 1) > 0) {
break;
} else if (a[i][j] == 1 && (width + 1) > 0) {
width++;
endRow = j;
endColumn = i;
} else if (a[i][j] == 1 && (width + 1) == 0) {
if (startRow < 0) {
startRow = j;
startColumn = i;
}
width++;
endRow = j;
endColumn = i;
}
}
if ((width + 1) > 0) {
int widthNext = 0;
for (int j = startColumn; j < a.length; j++) {
for (int k = startRow; k < endRow + 1; k++) {
if (a[j][k] == 1) {
widthNext++;
} else {
break;
}
}
if ((width + 1) == widthNext) {
for (int k = startRow; k < endRow + 1; k++) {
a[endColumn][k] = 0;
}
height++;
endColumn++;
widthNext = 0;
} else {
break;
}
}
count++;
i--;
}
startRow = -1;
startColumn = -1;
width = -1;
height = -1;
endRow = -1;
endColumn = -1;
}
return count;
}
}