【发布时间】:2014-05-17 15:13:52
【问题描述】:
1 1 0 0
0 0 0 0
0 0 0 0
1 1 0 0
如果以上是我的输入,我的代码应该会在其中找到四个连续的 1。 我知道我们必须使用环绕数组来解决这个问题,但我不知道如何实现它。 这是修改后的代码
public static boolean findFourOnes(int[][] arr){
for(int i = 0; i < arr.length; i++){
if(findVertical(arr, i, 0, 0)){
return true;
}
}
for(int i = 0; i < arr.length; i++){
if(findHorizontal(arr, 0, i, 0)){
return true;
}
}
return false;
}
public static boolean findVertical(int[][] arr, int x, int y, int counter){
//base case
if(counter == 4)
return true;
if(arr[x][y] == 1)//consecutive
counter++;
else//not consecutive
counter = 0;
y++;
// wrap around case
if(y == arr.length - 1|| y == arr.length +1){
int max_size=4;
if(y < 0) {y=x + max_size; return findVertical(arr, x, y, counter);}
else if(y >= max_size) {y=x % max_size;return findVertical(arr, x, y, counter);}
}
return false;
}
public static boolean findHorizontal(int[][] arr, int x, int y, int counter){
//base case
if(counter == 4)
return true;
if(arr[x][y] == 1)//consecutive
counter++;
else//not consecutive
counter = 0;
x++;
// wrap around case
if(x == arr.length - 1|| x == arr.length +1){
int max_size=4;
if(x < 0) {x=x + max_size; return findHorizontal(arr, x, y, counter);}
else if(x >= max_size) {x=x % max_size; return findHorizontal(arr, x, y, counter);}
}
return false;
}
此代码仅检查数组中是否有四个连续的 1。如果工作正常,
我的矩阵是 4X4。在这段代码中,我的数组 b 是空的,带有零。如果我找到四个 1,我会更新该矩阵。
【问题讨论】:
-
这是否意味着连续的 4 个可以是水平的、垂直的或对角的?你提到了环绕,但你的例子并没有真正的意义。您在寻找任何 4 组“1”吗?
-
它可以是水平和垂直的,但不能是对角线
-
这会引发很多
NullPointerExceptions,对吧?在if中使用价值null的Boolean应该可以做到这一点。还有你为什么要换b?
标签: java recursion data-structures