【发布时间】:2016-06-20 09:37:23
【问题描述】:
定义一个方法,给定一个二维整数数组,验证所有等于 1 的元素构建一个矩形。
这是我到现在为止的想法:
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 谢谢,确实 res 数组中没有任何内容,我会修复它
-
你的算法不正确,连你的代码都乱写了。您正在计算列中 1 的数量,但在哪一列??
-
@Prince 这也是真的……我可能不得不想出一个完全不同的算法