【发布时间】:2013-06-23 13:15:32
【问题描述】:
我正在尝试编写一个使用递归方法查找从二维数组开始到结束的路径数的程序。这些步骤应该从 [0][0] 开始直到结束。数组由 0 到 99 之间的整数填充。
对于数组中的每个数字都可以向前移动两个不同的步骤:例如,如果 [0][0] 是 21 ,则下一步可能是 [0+2][0+1] 或 [0+1][0 +2] 。 该方法应返回到达终点的不同路径的数量。
这是我的代码:
编译过程中方法获取[][]数组时发生溢出
public class two
{
int[][] _my=new int[0][0];
public two ()
{
}
static int count=0;
public static int count;
ountPath(int[][] mat)
{
int nextX=0;
int nextY=0;
int current=mat[0][0];
if (current<=9)
{
nextX=current;
nextY=current;
if (checkBorders(0,0,nextX,nextY,mat)==0)
{
return 0;
}
}
else
{
nextX=(int)current/10;
nextY=current%10;
if (checkBorders(0,0,nextX,nextY,mat)==0)
{
return 0;
}
}
countPath(mat,nextX,nextY);
countPath(mat,nextY,nextX);
return count;
}
public static int countPath(int[][] mat,int x,int y)
{
int current=mat[x][y];
int nextX=0;
int nextY=0;
int terminate=0;
if (current<=9)
{
nextX=current;
nextY=current;
if (checkBorders(x,y,nextX,nextY,mat)==0)
{
return 0;
}
}
else
{
nextX=(int)current/10;
nextY=current%10;
if (checkBorders(x,y,nextX,nextY,mat)==0)
{
return 0;
}
}
if (((mat.length-1)==nextY)&&((mat[0].length-1)==nextX))
{
terminate=1;
}
if (terminate==1)
count++;
else
{
countPath(mat,nextX,nextY);
countPath(mat,nextY,nextX);
}
return count;
}
public static int checkBorders(int x,int y,int x1,int y1,int[][] mat)
{
int maxX=mat[0].length;
int maxY=mat.length;
if ((x+x1)>maxX)
return 0;
else if ((y+y1)>maxY)
return 0;
else return 1;
}
}
请帮我修复代码。
【问题讨论】:
-
怎么不工作了?
count是静态变量吗?顺便说一句,在 java 中你可以使用boolean -
如果代码是自包含的,它不仅可以说明问题所在,还可以发布完整的代码。
-
是的,我使用静态计数变量。