我有一个整数数组。从第一个位置开始,然后我在给定索引处添加或减去该值以在数组中移动。这个难题的目的是到达数组的最后一个元素0.我知道这个问题已经通过递归解决了,但我应该给出一个非递归的解决方案。 为了避免无限循环,我创造了一个条件
if (a[index] == a[index+temp])
当我传递这样的数组时,代码工作正常:
int a [] = { 3, 1, 2, 3, 0 };
然后我通过了int a [] = {3, 6, 4, 3, 3, 4, 3, 5, 3, 0 }
,它告诉我这个谜题没有解决方案,但事实并非如此。
这是我的代码的一部分:
int temp;
int index = 0;
while (index < (a.length-1) && index >= 0)
{
temp = a[index];
if ((index+temp) <= a.length-1 )
{
if (a[index] == a[index+temp]){
solution = false;
break;
}
index = index + temp;
}
else if ((index-temp) >=0)
{
index = index - temp;
}
}
答案 0 :(得分:1)
这里你所拥有的基本上是一个定向的未加权图。每个索引都与1或2个其他索引相关联。
现在,考虑到这一点,您可以使用&#34; breadth first search&#34;轻松解决此问题。算法很好,没有递归。
这是一个非常详细的实现示例:https://ideone.com/yzeBzz
List<Integer> solve(int... a) {
//Value in each element is the index, from where we can come here
int[] path = new int[a.length];
Arrays.fill(path, -1); //No index is accessible yet
//Queue of positions that were visited from somewhere, but nothing was tried to be
//visited from them. At the beginning, 0 is in the list, because it's starting point.
//Then, if we visit index 3, it is added to this list for later processing.
Queue<Integer> posQueue = new LinkedList<>();
posQueue.add(0);
path[0] = 0; //0 index is accessible from itself, this is starting position
while (!posQueue.isEmpty()) {
int pos = posQueue.remove();
int prPos = pos - a[pos];
int nxPos = pos + a[pos];
if (prPos >= 0 && path[prPos] == -1) {
path[prPos] = pos;
posQueue.add(prPos);
}
if (nxPos < a.length && path[nxPos] == -1) {
path[nxPos] = pos;
posQueue.add(nxPos);
}
if (path[a.length-1] != -1) {
break;
}
}
if (path[a.length-1] == -1) {
return null;
}
//Collect the path
List<Integer> result = new ArrayList<>();
int idx = a.length-1;
while (idx != 0) {
result.add(0, idx);
idx = path[idx];
}
result.add(0, 0);
return result;
}
与任何广度搜索算法一样,复杂度为O(N)。
答案 1 :(得分:-1)
这可能有效:
boolean solve(int... a) {
for (int i = 0; i < 1 << a.length; i++) {
int pos = 0;
for (int j = 0; j < 32; j++) {
if ((i & (1 << j)) == 0) {
if ((pos -= a[pos]) < 0) {
break;
}
} else {
if ((pos += a[pos]) >= a.length) {
break;
}
}
if (a[pos] == 0) {
return true;
}
}
}
return false;
}