【发布时间】:2018-01-09 11:05:01
【问题描述】:
练习: 建立一个递归(没有循环),你进入的每个单元格都是你可以走的步数,它可以是右/左,直到你到达最后一个单元格。如果您无法到达最后一个单元格,则返回 false,否则返回 true。 您必须从索引 0 开始。
我的问题:我构建了程序,但它不工作,我能够到达最后一个单元格但在输出中我得到错误,我明白为什么我弄错了,但我不知道如何解决。
测试:
public static void main(String[] args)
{
// Q - isWay
System.out.println("\nTesting Question 3\n==================");
int[] a1 = {2,4,1,6,4,2,4,3,5};
System.out.println("a = {2,4,1,6,4,2,4,3,5}");
System.out.println("Ex14.isWay(a) is: " + Ex14.isWay(a1)); //need to return true
int[] a2 = {1,4,3,1,2,4,3};
System.out.println("a2 = {1,4,3,1,2,4,3}");
System.out.println("Ex14.isWay(a2) is: " + Ex14.isWay(a2));//need to return false
}
public class Ex14
{
public static boolean isWay(int[] a)
{
int i = 0;
if(a.length <= 1)
return false;
return isWay(a , 0);
}
public static boolean isWay(int[] a,int i)
{
int temp1 , temp2;
if(i == a.length-1)
return true;
if(!((a[i]+i < a.length) && (i-a[i] >= 0))) // can't go right and left
return false;
else if(a[i] > 0)
{
if(a[i]+i < a.length) // go right
{
temp1 = a[i] + i;
a[i] = -1;
return isWay(a, temp1);
}
else if (i-a[i] >= 0) // go left
{
temp2 = i - a[i];
a[i] = -1;
return isWay(a, temp2);
}
}
return false;
}
}
【问题讨论】:
-
好的......我不确定你在问什么。你能说得清楚一点吗?
-
当然,我是递归新手,现在我不明白我在递归中做得不好的地方总是错误的,我希望你能告诉我错误并解释我的错误我做错了。
-
在我看来你的递归有效,只是你实现的逻辑有缺陷
标签: java arrays recursion boolean