定义一个方法,给定一个二维整数数组,验证所有元素都等于1是否构成了一个矩形。
以下是我目前的想法:
以下是我目前的想法:
请参考下面的图片更好地理解:public static boolean isRectangle(int[][] arr) {
// TODO: Implement this method
}
public static boolean oneRectangle(int [][] a) {
boolean rectangle=true;
int[][] res;
int OneinRow=0; //keeps track of how many ones there are in the row
int OneinColoumn=0; //keeps track of how many ones there are in a coloumn
for(int i=0; i<a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
while (a[i][j] == 1) {
i++;
OneinRow++;
}
while (a[i][j] == 1) {
j++;
OneinColoumn++;
}
}
}
res = new int[OneinRow][OneinColoumn];
for(int k=0; k<res.length; k++)
for(int l=0; l<res[0].length; l++)
if(res[k][l] != 1)
rectangle = false;
return rectangle;
}
由于某些原因,它并不能按预期工作。
f = new int[][] {
{1,2,3,4}, //1 in position 0
{2,1,4,5}, //1 in position 1
{3,4,5,6}};
返回true
而不是false
。
我该如何修复和改进算法?
res
表在创建后只包含零,并且您不需要填充它任何其他内容。 - krzydyn