2011-11-27 20 views
2

我正嘗試在Java中編寫一個3x3的方形拼圖求解器。然而,我被卡在了我轉移塊的那一部分 - 我一直用我使用的算法結束了一堆新的空白空間。經過一些測試後,我確定這是因爲,儘管我使用了clone()命令,但當我更改「current」時,v的數組仍然受到影響。有誰知道這是爲什麼,我該如何解決它?我認爲使用克隆後,我可以更改新陣列而不影響舊陣列。我使用了克隆,但原始數組仍然受到影響

if (!rightwall) 
    { 
     int[][] current = v.state.clone(); 
     current[x][y] = current[x][y + 1]; 
     current[x][y + 1] = 0; 
     State w = new State(current); 
     w.distance = v.distance + 1; 
     w.path = v; 
     System.out.println("Right Shift:"); 
     w.print(); 
     q.insert(w); 
    } 

狀態是表示與一些性質沿着二維陣列的一類 - 對狀態的代碼的第一部分是

public class State { 
int[][] state = new int[3][3]; 
int distance = 0; 
boolean known = false; 
State path = null; 
State(int[][] newstate){ 
    state = newstate.clone(); 
} 

v是代表當前位置的狀態。那麼w就會成爲一個「鄰接」位置,它在切換空間旁邊的空間後創建。

q是一個隊列。

+0

什麼是'v'?什麼是'國家'?什麼是'q'?沒有任何這種上下文,這段代碼就沒有意義了。 – skaffman

回答

8

在您的州級課程中,您需要確保所有屬性都被深度複製。

+0

我該怎麼做?代碼是 public class State int [] [] state = new int [3] [3]; int distance = 0; boolean known = false; State path = null; (int [] [] newstate){ \t state = newstate.clone(); } –

+0

您應該在構造函數中實際創建一個新的數組實例,然後將該數組從源複製到目標 – allthenutsandbolts

+0

您剛剛克隆了數組數組。這意味着你有一個新的外部數組,持有對與舊外部數組相同的內部數組的引用。你也應該克隆所有的內部數組。請參閱http://stackoverflow.com/questions/5563157/how-to-deep-copy-2-dimensional-array-different-row-sizes –

相關問題