在Java中編寫遞歸函數(圖論),從一個隨機的起點開始,獲取4x4表中的所有路徑。可能的方向是水平的,垂直的&對角線,但我有一個要求,不能訪問兩次相同的位置。Java深度優先遞歸函數
到目前爲止,該腳本工作正常,我得到了很多組合。問題是,在函數的for循環中,當有多種可能的方式時,在第二個循環和下一個循環中我得到了錯誤的結果,因爲布爾型[]臨時值沒有回到他以前的值。
我希望有人能夠理解我的英語和我的問題。這是我到目前爲止的代碼:
// here I define a constant input of values:
String letters = "1548987425461854"
// This matrix shows all possible directions from every startpoint in the matrix:
// from the second value, you may get to the following locations: 1,3,5,6 and 7
private int[][] matrix = {
{1,4,5},
{0,2,4,5,6},
{1,3,5,6,7},
{2,6,7},
{0,1,5,8,9},
{0,1,2,4,6,8,9,10},
{1,2,3,5,7,9,10,11},
{2,3,6,10,11},
{4,5,9,12,13},
{4,5,6,8,10,12,13,14},
{5,6,7,9,11,13,14,15},
{6,7,10,14,15},
{8,9,13},
{8,9,10,12,14},
{9,10,11,13,15},
{10,11,14}
};
// Here begins the recursive function
public List<Combination> depthFirst(int vertex, boolean[] visited, Combination zeichen, List<Combination> combis){
// A temporary list of booleans to mark every value position visited or not
boolean[] tempvisited = new boolean[16];
// combis is the whole list of ways, zeichen is just the actual combination
zeichen.name = zeichen.name + this.letters.charAt(vertex);
combis.add(zeichen.name);
//marks actual value as visited
visited[vertex] = true;
for(int i = 0; i < 16; i++){
tempvisited[i] = visited[i];
}//end for
// going to next possible locations
for (int i = 0; i < this.matrix[vertex].length; i++) {
if (!visited[this.matrix[vertex][i]]) {
combis = depthFirst(this.matrix[vertex][i], tempvisited, zeichen, combis);
}//end if
}//end for
return combis;
}
嗯,謝謝,但這會減慢腳本很多,並在內存不足的錯誤結束 – Jokus 2013-03-12 19:28:42