代码如下:
public class TestQuestion {
private String[] b = new String[] { "1", "2", "2", "3", "4", "5" };
private int n = b.length;
private boolean[] visited = new boolean[n];
private int[][] a = new int[n][n];
private String result = "";
private TreeSet<String> set = new TreeSet<String>();
public static void main(String[] args) {
new TestQuestion().start();
}
private void start() {
// Initial the map a[][]
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
a[i][j] = 0;
} else {
a[i][j] = 1;
}
}
}
// 3 and 5 can not be the neighbor.
a[3][5] = 0;
a[5][3] = 0;
// Begin to depth search.
for (int i = 0; i < n; i++) {
this.depthFirstSearch(i);
}
// Print result treeset.
int total = 0;
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String str = (String) it.next();
// "4" can not be the third position.
if (str.indexOf("4") != 2) {
System.out.println(str);
total++;
}
}
System.out.println("总数:" + total);
}
private void depthFirstSearch(int startIndex) {
visited[startIndex] = true;
result = result + b[startIndex];
if (result.length() == n) {
// Filter the duplicate value.
set.add(result);
}
for (int j = 0; j < n; j++) {
if (a[startIndex][j] == 1 && visited[j] == false) {
depthFirstSearch(j);
} else {
continue;
}
}
// restore the result value and visited value after listing a node.
result = result.substring(0, result.length() - 1);
visited[startIndex] = false;
}
}
调试的时候,当程序运行到函数depthFirstSearch的最后一行时,为什么又跳回到该函数的for循环处继续执行
[quote]同学请看清楚,for里面执行的是continue,已经跳出循环了,递归该结束了 [/quote]
有这种情况,第一次执行的时候,进入的是 if 分支,那么就会再一次的调用你的 depthFirstSearch 方法,但是前一次的 depthFirstSearch 方法还没有执行完毕。当第二次的 depthFirstSearch 方法调用执行完毕了之后,就会回到第一次的 depthFirstSearch 方法中继续执行,就是你看到的现象
[quote]
} else {
continue;
}
[/quote]
是 continue 在起作用。这个关键字的含义是:结束当前循环,进行下一次的循环。
如果你是想跳出循环,那么请把它换成 [quote]break[/quote]
不是有递归调用嘛!这有什么好“为什么”的
童鞋你让我很无语
你在depthFirstSearch方法的for循环里递归调用depthFirstSearch,递归调用返回当然就在for循环里啦,话说回来,递归的概念你知道不?这和continue有啥子关系,除非程序一直都执行的是continue那条分支而不存在递归调用depthFirstSearch
你的代码没有缩进,看起来有点麻烦。我上面的说错了。
[quote]
下面这两句没包括在for语句里的
result = result.substring(0, result.length() - 1);
visited[startIndex] = false;
[/quote]
正是因为没有放在 for 里,所以你的
[quote]当程序运行到函数depthFirstSearch的最后一行时,为什么又跳回到该函数的for循环处继续执行[/quote]
中“最后一行”是不是指的是
[quote]continue; [/quote]
这句话啊?如果是的话,请你看我第一次给你发的那个回复,也请你复习一下 continue 与 break 这两个关键字的作用