题目:给定一个无向图,给出它的深度遍历
先给出图
从S出发,按照字母顺序深度遍历图可得出的结果:SABCDEFGH
这个图十分的特殊,可以检测到有些错误的遍历方法,有些错误的遍历方法有时候可以通过简单的图,但是这张图是不行的,至于如何证明,笔者这里不多加证明
下面给出我的代码:
import java.util.Stack;
public class bianli {
private Object[] jiedian;//存储节点
private int num;//节点个数
private int juzhen[][];//邻接矩阵
private boolean visit[];//判断是否遍历
// 初始化
public bianli(int n) {
num = n;
juzhen = new int[n][n];
jiedian = new Object[n];
visit = new boolean[n];
for (int i = 0; i < n; i++) {
visit[i] = false;
for (int j = 0; j < n; j++) {
juzhen[i][j] = 0;
}
}
}
//初始化节点
public void addjiedian(Object ob[]) {
this.jiedian = ob;
}
//初始化边
public void addbian(int i, int j) {
if (i == j)
return;
else {
juzhen[i][j] = 1;
juzhen[j][i] = 1;
}
}
//遍历边
public void visit(int n) {
visit[n] = true;
System.out.print(jiedian[n]);
}
//第一个邻接点
public int firstAdjcent(int i) {
for (int j = 0; j < num; j++) {
if (juzhen[i][j] > 0 && visit[j] == false) {
return j;
}
}
return -1;
}
// i 节点后其余的邻接点
public int nextAdjcent(int i, int k) {
for (int j = k + 1; j < num; j++) {
if (juzhen[i][j] > 0 && visit[j] == false) {
return j;
}
}
return -1;
}
// 递归深度遍历
public void deptravel() {
System.out.println("递归深度遍历:");
for (int j = 0; j < num; j++) {
if (!visit[j]) {
this.travel(j);
}
}
}
public void travel(int i) {
if (visit[i] == false) {
this.visit(i);//如果没有遍历就遍历
for (int j = this.firstAdjcent(i); j >= 0; j = this.nextAdjcent(i,
j)) {
if (!visit[j]) {
this.travel(j);//找到i的邻接点然后递归遍历
}
}
}
}
// 非递归遍历
public void dptravel() {
Stack stack = new Stack();
for (int i = 0; i < num; i++) {
visit[i] = false;
}
System.out.println("非递归遍历");
for (int i = 0; i < num; i++) {
if (!visit[i]) {
stack.push(i);
while (!stack.isEmpty()) {
int j = (Integer) stack.pop();
if (!visit[j]) {
this.visit(j);//将母节点遍历,然后将它的子节点按照字母逆序入栈,这样可以在栈顶访问它的最近邻接点,继续将它的邻接点入栈,每次其实都是访问的它的最近邻接点,这样出栈的顺序就是访问的顺序
for (int k = num - 1; k > 0; k--) {
if (juzhen[j][k] > 0 && visit[k] == false) {
stack.push(k);
}
}
}
}
}
}
}
public static void main(String[] args) {
bianli test = new bianli(9);
Character jiandian[] = { 'S', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
test.addjiedian(jiandian);
test.addbian(0, 1);
test.addbian(0, 5);
test.addbian(1, 2);
test.addbian(1, 4);
test.addbian(2, 3);
test.addbian(3, 8);
test.addbian(3, 4);
test.addbian(4, 7);
test.addbian(4, 5);
test.addbian(5, 6);
test.addbian(6, 7);
test.addbian(7, 8);
test.deptravel();
System.out.println();
test.dptravel();
}
}