我有一個整數數組。從第一個位置開始,我然後在給定索引處添加或減去值以在數組中移動。這個謎題的目的是到達數組的最後一個元素0。我知道這個問題已經在遞歸中解決了,但我應該給出一個非遞歸解決方案。 爲了避免無限循環,我提出一個條件Java拼圖在整數陣列中左右移動
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;
}
}
你能解釋一下在手的算法多一點?我真的不明白「右移」和「左移」實際上是如何發生的......(如:爲什麼在步驟2中「向右移動」停在1 ...?) – MordechayS
他應該嘗試兩個方向我認爲,無論哪一個導致解決方案。 –
@MordechayS當我在起始位置時,值是3.我只能向右移動三個位置。在位置a [3]處,值爲1,所以我可以向右或向左移動。 – q212