采用二维数组定义图结构,最后的代码是:
1
package test;
import java.util.Iterator;
import java.util.TreeSet;
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 treeSet = new TreeSet();// 用于保存结果,具有过滤相同结果的作用。
public static void main(String[] args) {
new TestQuestion().start();
}
private void start() {
// 创建合法路径标识集合
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;
}
}
}
a[3][5] = 0;
a[5][3] = 0;
for (int i = 0; i < n; i++) {
this.depthFirstSearch(i);// 深度递归遍历
}
Iterator it = treeSet.iterator();
while (it.hasNext()) {
String string = (String) it.next();
if (string.indexOf("4") != 2) {
System.out.println(string);
}
}
}
/**
* 深度优先遍历
*
* @param startIndex
*/
private void depthFirstSearch(int startIndex) {
// 递归的工作
visited[startIndex] = true;// 用于标识已经走过的节点
result = result + b[startIndex];// 构造结果
if (result.length() == n) {
treeSet.add(result);// 添加到TreeSet类型中,具有过滤相同结果的作用
}
// 每走到一个节点,挨个遍历下一个节点
for (int j = 0; j < n; j++) {
if (a[startIndex][j] == 1 && visited[j] == false) {
depthFirstSearch(j);// 深度递归遍历
} else {
continue;
}
}
// 递归的收尾工作
result = result.substring(0, result.length() - 1);
visited[startIndex] = false;// 取消访问标识
}
}
发表于 @ 2008年03月27日 16:03:00 | 评论( loading... ) | 举报| 收藏