我想解決着名的8難題,其中一個3 * 3方塊充滿了1個空插槽和8個數字,解決方法是將其返回到原始狀態。通過引用vs按值java
要做到這一點,我有一個「狀態」arraylist存儲數字0〜9,代表拼圖。
解決方案涉及產生許多可能的移動狀態,這意味着我保存所做的每一個合法移動和由此產生的難題。這是使用下面的方法完成的,但是我的swapAndStore不會每次都編輯原始傳遞的數組。相反,當在下面的genSuccessors()中調用時,它將對第一個if條件正常工作,然後對第一個if的結果應用next if條件。我認爲我通過製作一個名爲「oldBoard」的新益智遊戲來解決這個問題,以保存原始輸入難題供將來參考,但這也不起作用。一位朋友告訴我,這可能與我無法很好把握的參考問題有關。我知道當x = 0,y = 1時,java不會做交換(x,y),所以x = 1,y = 0,但是看不到這在這裏如何適用。 意見?
private void swapAndStore(int d1, int d2, ArrayList<State> s)
{
//int[] cpy = copyBoard(curBoard);
int[] cpy = new int [curBoard.length];
System.arraycopy(curBoard,0,cpy,0,curBoard.length);
int[] oldBoard = new int [curBoard.length];
System.arraycopy(curBoard,0,oldBoard,0,curBoard.length);
int temp = cpy[d1];
cpy[d1] = cpy[d2];
cpy[d2] = temp;
s.add((new State(cpy)));
curBoard = oldBoard;
System.out.println("swapandstore storing");
s.get(s.size()-1).printState();
}
public ArrayList<State> genSuccessors()
{
ArrayList<State> successors = new ArrayList<State>();
int hole = getHole();
// try to generate a state by sliding a tile leftwise into the hole
// if we CAN slide into the hole
if (hole != 0 && hole != 3 && hole != 6)
{
/*
* we can slide leftwise into the hole, so generate a new state for
* this condition and throw it into successors
*/;
System.out.println("left");
swapAndStore(hole - 1, hole, successors);
}
// try to generate a state by sliding a tile topwise into the hole
if (hole != 6 && hole != 7 && hole != 8)
{
System.out.println("top");
swapAndStore(hole + 3, hole, successors);
}
ü可能想補充一下: TL;博士; :) – DarthVader
我不知道我明白。 – duffymo
@DarthVader說他有一個閱讀理解問題:D –