【发布时间】:2014-04-22 01:53:48
【问题描述】:
我正在尝试在矩阵中递归查找一个数字。
public class Test2 {
static char arry [][] = {{'#','#','#'},
{'#',' ',' '},
{'#',' ','#'},
{'#',' ','1'},
};
public static void main(String args []){
recursion(2,1);
}
private static void recursion(int row, int col) {
if(arry[row][col]=='1' && isInBound(row,col)==true){
System.out.println("Found at " + row + " " + col);
}else if ((isInBound(row,col)==true)&& arry[row][col]==' '){
recursion(row,col+1);
recursion(row,col-1);
recursion(row-1,col);
recursion(row+1,col);
}
}
private static boolean isInBound(int row, int col) {
boolean bol = false;
if(row<= arry.length && col <= arry[0].length){
bol = true;
}
return bol;
}
}
我正在尝试以能够从任何位置开始的方式来制作程序。例如,我从这个程序中的 2,1 位置开始。我得到了一个越界异常。在使用 try catch 循环时,代码有时适用于某些输入。除非绝对必要,否则我不想使用 try catch。我也在尝试在矩阵中寻找所有 4 个方向。这就是我的问题开始的地方,我要越界了。
【问题讨论】:
-
修复此错误后,您将需要以某种方式跟踪访问过的单元格,否则您的搜索将在两个单元格之间来回摆动,直到堆栈溢出。
标签: java arrays recursion matrix