[英]Java Puzzle moving left and right in an array of integers
我有一個整數數組。 從第一個位置開始,然后添加或減去給定索引處的值以在數組中移動。 難題的目的是到達數組的最后一個元素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 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;
}
}
您基本上擁有的是有向無權圖。 每個索引都與1個或2個其他索引相連。
現在,考慮到這一點,您可以使用“ 廣度優先搜索 ”算法輕松解決此問題,該算法無需遞歸即可很好地工作。
這是非常詳細的實現示例: 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)。
這可能起作用:
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.